c# - 有没有办法从作为任务运行的同步方法调用异步?
问题描述
让我从一些代码开始。我有一个异步数据通道:
interface IChannel
{
Task<byte[]> SendRecv(string command, byte[] request);
}
以及描述可以在远程服务器上执行的操作的同步接口:
interface IRemoteServer
{
int DoLongTask(int param);
}
以及使用异步数据通道的实现:
class RemoteServer : IRemoteServer
{
private IChannel _channel;
public int DoLongTask(int param)
{
var request = BitConverter.GetBytes(param);
var response = _channel.SendRecv(nameof(DoLongTask), request).Result;
return BitConverter.ToInt32(response, 0);
}
}
最后是异步编写并使用远程服务器抽象的应用程序:
class Application
{
private IRemoteServer _server;
async Task<int> SomeMethod(int param)
{
return await Task.Run(() => _server.DoLongTask(param));
}
}
上面代码的问题是,尽管通道和应用程序都是异步编写的,但在访问Result
远程服务器实现时会阻塞线程池线程。让我们假设它IRemoteServer
是不可变的,因为它在其他地方使用过,而且我无法直接控制它的外观。现在,在实现接口(类RemoteServer
)时,我不能使用这个async
词,因为 C# 假定它是简单的同步方法 - 另一方面,我知道在执行该方法时我已经在一个任务中,所以理论上我可以async
在运行时使用加入两个任务(Application.SomeMethod
和IChannel.SendRecv
)。
我正在寻找这个问题的解决方案(包括低级/高级黑客),任何帮助表示赞赏!
解决方案
推荐阅读
- linux - 无法编译linux内核版本3.16
- sql-server - 尝试从云功能连接到 Cloud-sql sql-server 时出现连接错误
- node.js - 浏览器版本 - expressjs / morgan
- python - 使用 heredoc 而不是文件路径为 Python Kubernetes 客户端提供数据
- python - django 从另一个没有 ForeignKey 的模型填充模型字段
- php - 无法下载 pdf - Laravel
- ruby-on-rails - Rails:在许多控制器之间传递用户状态
- javascript - Javascript - .sort() 返回与原始数组相同
- android - 构建提示以扩展通知或使用带有 CodenameOne 推送消息的通知组
- python - 将两个二进制文件合并为第三个二进制文件