你正在执行一个远程调用,你的线程需要等待远程调用的结果。在此等待期间,您的线程可以做一些有用的事情,例如执行其他远程调用。
当您的线程空闲地等待其他进程完成时,例如写入磁盘、查询数据库或从 Internet 获取信息,通常是您会在非异步函数旁边看到异步函数的情况: Write 和 WriteAsync、Send 和 SendAsync。
如果在同步调用的最深层,您可以访问调用的异步版本,那么您的生活会很轻松。唉,看来你没有这样的异步版本。
您提出的使用Task.Run 的解决方案的缺点是启动一个新线程(或从线程池运行一个线程)会产生开销。
您可以通过创建工作室对象来降低此开销。在车间中,一个专用线程(一个工人),或几个专用线程在一个输入点等待一个命令来做某事。线程执行任务并将结果发布到输出点。
研讨会的用户有一个访问点(前台?),他们可以在此发布请求做某事,然后等待结果。
为此,我使用了System.Threading.Tasks.Dataflow.BufferBlock。安装 Nuget 包 TPL Dataflow。
您可以将您的工作坊专用于只接受GetDataTakingLotsOfTime 的工作;我让我的工作坊变得通用:我接受所有实现接口 IWork 的工作:
interface IWork
{
void DoWork();
}
WorkShop 有两个BufferBlocks:一个输入工作请求,一个输出完成的工作。车间有一个线程(或多个线程)在输入 BufferBlock 处等待,直到作业到达。是否Work,完成后将作业发布到输出BufferBlock
class WorkShop
{
public WorkShop()
{
this.workRequests = new BufferBlock<IWork>();
this.finishedWork = new BufferBlock<IWork>();
this.frontOffice = new FrontOffice(this.workRequests, this.finishedWork);
}
private readonly BufferBlock<IWork> workRequests;
private readonly BufferBlock<IWork> finishedWork;
private readonly FrontOffice frontOffice;
public FrontOffice {get{return this.frontOffice;} }
public async Task StartWorkingAsync(CancellationToken token)
{
while (await this.workRequests.OutputAvailableAsync(token)
{ // some work request at the input buffer
IWork requestedWork = this.workRequests.ReceiveAsync(token);
requestedWork.DoWork();
this.FinishedWork.Post(requestedWork);
}
// if here: no work expected anymore:
this.FinishedWork.Complete();
}
// function to close the WorkShop
public async Task CloseShopAsync()
{
// signal that no more work is to be expected:
this.WorkRequests.Complete();
// await until the worker has finished his last job for the day:
await this.FinishedWork.Completion();
}
}
TODO:对 CancellationToken.CancellationRequested 的正确反应
TODO:对工作引发的异常做出适当反应
TODO:决定是否使用多个线程来完成工作
FrontOffice 有一个异步函数,它接受工作,将工作发送到 WorkRequests 并等待工作完成:
public async Task<IWork> OrderWorkAsync(IWork work, CancellationToken token)
{
await this.WorkRequests.SendAsync(work, token);
IWork finishedWork = await this.FinishedWork.ReceivedAsync(token);
return finishedWork;
}
因此,您的进程创建了一个 WorkShop 对象并启动一个或多个将 StartWorking 的线程。
每当任何线程(包括您的主线程)需要以异步等待方式执行一些工作时:
- 创建一个保存输入参数和 DoWork 函数的对象
- 向工作室咨询 FrontOffice
- 等待 OrderWorkAsync
.
class InformationGetter : IWork
{
public int Id {get; set;} // the input Id
public Data FetchedData {get; private set;} // the result from Remoting.GetData(id);
public void DoWork()
{
this.FetchedData = remoting.GetData(this.Id);
}
}
最后是你的遥控器的异步版本
async Task<Data> RemoteGetDataAsync(int id)
{
// create the job to get the information:
InformationGetter infoGetter = new InformationGetter() {Id = id};
// go to the front office of the workshop and order to do the job
await this.MyWorkShop.FrontOffice.OrderWorkAsync(infoGetter);
return infoGetter.FetchedData;
}