Reputation: 201
Example: Once I display a messagebox, I'd like to call into a function to automatically exit the environment AFTER 5 seconds of the messagebox being displayed.
Is there a better approach towards doing so other than using a timer (starting the timer before the messagebox is displayed)?
Thanks
Upvotes: 0
Views: 41
Reputation: 9587
Using a timer is definitely a valid solution in this case, but you can also leverage Task
s and async/await
in order to gain more control over the execution flow. Here's a Task
-based implementation which calls Environment.Exit(0)
after the predefined time interval, or immediately after the user dismisses the message box:
static void ShowMessageBoxAndExit(string text, TimeSpan exitAfter)
{
using (CancellationTokenSource cts = new CancellationTokenSource())
{
Func<Task> exitTaskFactory = async () =>
{
try
{
await Task.Delay(exitAfter, cts.Token).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
// Expected if the user dismisses the
// message box before the wait is completed.
}
finally
{
Environment.Exit(0);
}
};
// Start the task.
Task exitTask = exitTaskFactory();
MessageBox.Show(text);
// Cancel the wait if the user dismisses the
// message box before our delay time elapses.
cts.Cancel();
// We don't want the user to be able to perform any more UI work,
// so we'll deliberately block the current thread until our exitTask
// completes. This also propagates task exceptions (if any).
exitTask.GetAwaiter().GetResult();
}
}
Upvotes: 1