If you have a Dispatcher and want to be in the UI (Dispatcher) thread, use this:
void MyNonAsyncFunction()
{
Dispatcher.InvokeAsync(async () =>
{
await Task.Delay(1000);
MessageBox.Show("Thank you for waiting");
});
}
This function is not async because you did not want to wait within your function. This approach might be useful if you wanted to schedule more than one events at different times, but perhaps you really want the approach below:
async void MyAsyncFunction()
{
// Do my other things
await Task.Delay(1000);
MessageBox.Show("Thank you for waiting");
}
Which does the same thing, but requires the await to happen at the end of your function.
Since you may not have a Dispatcher or want to use it, but still want to schedule multiple operations at different times, I would use a thread:
static void MyFunction()
{
// Do other things...
Schedule(1000, delegate
{
System.Diagnostics.Debug.WriteLine("Thanks for waiting");
});
}
static void Schedule(int delayMs, Action action)
{
#if DONT_USE_THREADPOOL
// If use of threadpool is undesired:
new System.Threading.Thread(async () =>
{
await Task.Delay(delayMs);
action();
}
).Start(); // No need to store the thread object, just fire and forget
#else
// Using the threadpool:
Task.Run(async delegate
{
await Task.Delay(delayMs);
action();
});
#endif
}
If you want to avoid async, I would recommend not using the threadpool and replacing the await Task.Delay(delayMs)
call with a Thread.Sleep(delayMs)
call