Is it possible to use the "asynchronous" ThreadStart method?

I have a windows service that uses Thread and SemaphoreSlim to do some β€œwork” every 60 seconds.

class Daemon { private SemaphoreSlim _semaphore; private Thread _thread; public void Stop() { _semaphore.Release(); _thread.Join(); } public void Start() { _semaphore = new SemaphoreSlim(0); _thread = new Thread(DoWork); _thread.Start(); } private void DoWork() { while (true) { // Do some work here // Wait for 60 seconds, or exit if the Semaphore is released if (_semaphore.Wait(60 * 1000)) { return; } } } } 

I would call an asynchronous method from DoWork . To use the await keyword, I have to add async to DoWork :

 private async void DoWork() 
  • Is there any reason not to do this?
  • Can DoWork really work asynchronously if it is already running inside a dedicated thread?
+5
source share
1 answer

You can do it, but that would be nice. As soon as the first await hits that are not executed synchronously, the rest of the work will be performed on a continuation, and not on the thread you started ( _thread ); the starting thread ends on the first such await . There is no guarantee that the continuation will return to the original stream, and in your scenario it cannot - this stream is now a toast. It means that:

  • _thread is meaningless and does not represent the state of the operation; as such, your Stop() method with _thread.Join(); does not fulfill what you expect from him.
  • you created a thread (allocating threads is expensive, in particular because of the size of the stack), only to close it almost immediately.

Both of these problems can be avoided by using Task.Run to run such operations.

+5
source

Source: https://habr.com/ru/post/1268543/


All Articles