I have a Windows Service that uses Thread and SemaphoreSlim to perform 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'd like to call an asynchronous method from DoWork
. In order to use the await
keyword I must add async
to DoWork
:
private async void DoWork()
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:
_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 doBoth of these issues can avoided by using Task.Run
to start such operations.