Is it ok to use “async” with a ThreadStart method?

前端 未结 1 1010
清酒与你
清酒与你 2020-12-18 22:48

I have a Windows Service that uses Thread and SemaphoreSlim to perform some \"work\" every 60 seconds.

class Daemon
{
    private SemaphoreSlim _semaphore;
          


        
相关标签:
1条回答
  • 2020-12-18 23:19

    You can do this, but it wouldn't be a good idea. As soon as the first await hits that is not synchronously completed, the rest of the work will be done on a continuation, not the thread you started (_thread); the thread you start will terminate at the first such await. There is no guarantee that a continuation will go back to the originating thread, and in your scenario, it cannot - that thread is now toast. That means that:

    1. _thread is meaningless and does not represent the state of the operation; as such, your Stop() method with a _thread.Join(); doesn't do what you expect it to do
    2. you've created a thread (allocating threads is expensive, in particular because of the size of the stack) only to have it exit almost immediately

    Both of these issues can avoided by using Task.Run to start such operations.

    0 讨论(0)
提交回复
热议问题