Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
277 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...