问题
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