实施例: 一旦我显示了一个消息框,我想调用一个函数,在消息框显示5秒后自动退出环境。
除了使用计时器(在显示消息框之前启动计时器)之外,还有更好的方法吗?
由于
答案 0 :(得分:1)
在这种情况下,使用计时器绝对是一种有效的解决方案,但您也可以利用Task
和async/await
来获得对执行流程的更多控制。这是一个基于Task
的实现,在预定义的时间间隔后调用Environment.Exit(0)
,或者在用户解除消息框后立即调用:
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();
}
}