Several times, I have found myself writing long-running async methods for things like polling loops. These methods might look something like this:
private async Task PollLoop() { while (this.KeepPolling) { var response = await someHttpClient.GetAsync(...).ConfigureAwait(false); var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); // do something with content await Task.Delay(timeBetweenPolls).ConfigureAwait(false); } } The goal of using async for this purpose is that we don't need a dedicated polling thread and yet the logic is (to me) easier to understand than using something like a timer directly (also, no need to worry about reentrance).
My question is, what is the preferred method for launching such a loop from a synchronous context? I can think of at least 2 approaches:
var pollingTask = Task.Run(async () => await this.PollLoop()); // or var pollingTask = this.PollLoop(); In either case, I can respond to exceptions using ContinueWith(). My main understanding of the difference between these two methods is that the first will initially start looping on a thread-pool thread, whereas the second will run on the current thread until the first await. Is this true? Are there other things to consider or better approaches to try?
Task.Run2) because ofawait(generated by compiler) 3) PollLoop itself. On the other hand second one has only 1 Task.Task.Run(() => this.PollLoop().Wait())Task.Runanyway.await Task.Delay(10);on the beginning