How do I ThreadStart a method that is labelled async?

半腔热情 提交于 2020-02-08 10:44:35

问题


I want to run a processing loop on a separate thread:

_processingThread = new Thread(new ThreadStart(DoWork)));

But DoWork needs to be async:

private async Task QueueProcessorDoWork()
{
   while (true)
   {
     await something();
   }
}

How can I connect the two together? When I add async Task, it doesn't match the parameter of ThreadStart.

It is possible to make the method that sets up the thread async Task, I think, but I am not sure if that would help.

What's the best solution here? I need my thread to start running then return.


回答1:


This will queue the specified work to run on the ThreadPool.

_ = Task.Run(() => QueueProcessorDoWork());

QueueProcessorDoWork now has to be completely self sufficient and take care of itself. Any exceptions thrown will not be caught. The calling thread has no way of knowing if it's been successful or otherwise.

The _ = just stops the compiler warning that the call is not awaited.



来源:https://stackoverflow.com/questions/60002701/how-do-i-threadstart-a-method-that-is-labelled-async

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!