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()
- Is there any reason not to do this?
- Is DoWork actually able to run asynchronously, if it's already running inside a dedicated thread?
DoWork
async and not start new thread for it, but that depends on what exactlyDoWork
is doing and why you need to make it async. – Carbonateasync
anonymous methods inTask.Run()
is a common enough pattern, and it's functionally equivalent to what you're asking. Your question is primarily opinion based, and yes there are reasons not to do it, but probably not any really good ones. Do note that, just as in theTask.Run()
scenario, your thread will exit as soon as the firstawait
is reached. – LyneaCancellationTokenSource
, which works very well with the TPL API. – Lyneaasync
toDoWork()
the code still works. But I don't know async/await well enough to understand what's actually happening with that dedicated thread. The use ofawait
means that the method exits, and will continue later, correct? But if that's happening, what prevents the Thread from exiting? – Pantryawait
; pedantic point, perhaps, but ... sometimes it matters – Goeger