I've been researching this for a while but it seems things have changed over the years and there are some conflicting answers.
The way I would traditionally have done it is, in my OnStart
method,
new Thread(new ThreadStart(QueueProcessorDoWork));
So that it kicks off the thread then immediately returns.
And then:
private void QueueProcessorDoWork()
{
while (_isRunning)
{
DoStuff();
Thread.Sleep(100);
}
}
There is no way to make the DoStuff() a blocking operation, it has to basically poll.
Now, Thread.Sleep
is considered bad practice because it locks up the thread.
So research has showed me that I can use a timer. No problem with that, I would create a timer, and set it to poll every 100ms, and in the timer handler, I would disable the timer, do the processing, re-enable the timer again, and we'd be all good.
However I then read about using async/await with Task.Delay(100)
.
That sounds good. I would still need to create a Thread
, I believe, because otherwise the OnStart method wouldn't return. However this is unclear, if I call an async method without awaiting it, I don't know what would happen.
So question 1 is - should I just call an async Task that contains the infinite loop without awaiting it to start my windows service?
If I do want to use async/await within a thread, how exactly do I go about getting started? My ThreadStart can call a function that in turn does Task.Run(async () => Worker())
or something, I am not sure since the caller would need to be marked async?
So question 2 is, how would I set up the async/await pattern within a call to new Thread()
?
And the final question is, which (or both?) of the two method are the 'correct' way to start an infinite processing loop?