Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Schedule task and continue, in C#

Tags:

c#

async-await

I want my code to schedule a task and immediately proceed to ForeverRunningTaskAsync. This way StopForeverRunningTask executes while ForeverRunningTaskAsync is already in progress for 5 seconds:

private async void button_Click(object sender, RoutedEventArgs e)
{
  Task.Delay(5000).ContinueWith((t) => { StopForeverRunningTask(); }, CancellationToken.None);
  await ForeverRunningTaskAsync();
}

Everything's working fine at runtime. However, the compiler warns me that I missed 'await' in Task.Delay call. I don't want to await because ForeverRunningTaskAsync must start immediately, not after the delay. Perhaps, there is a more elegant method of scheduling a task and proceeding to the subsequent code immediately? Or, should I just ignore the warning?

EDIT: StopForeverRunningTask can actually do anything. From the answers, I see I should have provided more abstract name for it. It does not necessarily stops execution of ForeverRunningTask. It can set some flags, get current state, etc (and even be called multiple times during ForeverRunningTask runtime) so using CancellationToken is not an option. WaitAll approach suggested below answers my question.

like image 992
Alex Avatar asked Jun 15 '26 00:06

Alex


1 Answers

Its generally not a good idea to ignore that kind of warning. In some contexts it may not have any obvious immediate impact (like in your case) but it leave code fragile to any changes around it.

One of the options that you have is to wait until both tasks are done

private async void button_Click(object sender, RoutedEventArgs e)
{
  var stopper = Task.Delay(5000).ContinueWith((t) => { StopForeverRunningTask(); }, CancellationToken.None);
  var runner = ForeverRunningTaskAsync();
  await Task.WhenAll(stopper, runner);
}
like image 52
Oleg Bogdanov Avatar answered Jun 16 '26 12:06

Oleg Bogdanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!