简体   繁体   English

任务在另一个线程上异步运行 .NET

[英]Task running asynchronously on another thread .NET

I have a procedure that needs to be executed on another thread, asynchronously.我有一个需要在另一个线程上异步执行的过程。 The procedure will process a number of data in batches (can receive 2 items or 40000).该程序将批量处理多个数据(可以接收 2 个项目或 40000 个)。 From local tests, the longest runtime was about 2 minutes (for 40000 items).从本地测试来看,最长的运行时间约为 2 分钟(40000 个项目)。

The scenario is the following: UI call to back-end, back-end starts an asynchronous thread that will run the procedure and then returns a boolean, to know if the request was received or not (these are the requirements, I do not use await/wait).场景如下:UI调用后端,后端启动一个异步线程,该线程将运行该程序,然后返回一个boolean,以了解是否收到请求(这些是要求,我不使用等待/等待)。 I am not quite sure what to use here, between:我不太确定在这里使用什么,在:

Task.Run(()=> MyProcedure())

OR或者

Task.Factory.StartNew(()=> MyProcedure(), TaskCreationOptions.LongRunning)

What would be the best option for this situation?对于这种情况,最好的选择是什么?

The procedure will process a number of data in batches该程序将批量处理多个数据

This can mean multiple things.这可能意味着多件事。 If you are going to use async / await in those batches, such that your MyProcedure is actually asynchronous , then you should be fine with Task.Run ;如果您要在这些批次中使用async / await ,这样您的MyProcedure实际上是 asynchronous ,那么您应该可以使用Task.Run the fact that MyProcedure releases itself back to the thread-pool whenever it has gone async means that this should work fine, for example: MyProcedure在异步时将自身释放回线程池这一事实意味着这应该可以正常工作,例如:

async Task MyProcedure()
{
    while (ThereIsWorkToDo)
    {
       var batch = // ... gather some work
       await ProcessBatchAsync(batch).ConfigureAwait(false);
    }
}

However: if MyProcedure() is not asynchronous, but you just want to run it in the background, then yes, TaskCreationOptions.LongRunning might be reasonable, but for something that takes 2 minutes: so might be a regular dedicated thread.但是:如果MyProcedure()不是异步的,但您只想在后台运行它,那么是的, TaskCreationOptions.LongRunning可能是合理的,但需要 2 分钟:所以可能是一个常规的专用线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM