.NET 4.0 的变体:
void Button_Click(object sender, RoutedEventArgs e)
{
var t = StartAndWaitProcess(@"some\document\path");
t.ContinueWith(dummy => b.Content = "process finished",
TaskScheduler.FromCurrentSynchronizationContext());
}
Task StartAndWaitProcess(string path)
{
var p = new Process();
p.StartInfo.FileName = path;
p.EnableRaisingEvents = true;
var tcs = new TaskCompletionSource<bool>();
p.Exited += (sender, args) => { tcs.SetResult(true); p.Dispose(); };
Task.Factory.StartNew(() => p.Start());
return tcs.Task;
}
对于 .NET 4.5,有一个更好的选择
async void Button_Click(object sender, RoutedEventArgs e)
{
await StartAndWaitProcess(@"some\document\path");
b.Content = "process finished";
}
(StartAndWaitProcess
是一样的。)
旧代码,保持一致性:
async void Button_Click(object sender, RoutedEventArgs e)
{
var t = Task.Run(() => StartAndWaitProcess(@"some\document\path"));
await t;
label.Content = "process finished";
}
void StartAndWaitProcess(string path)
{
using(var p = Process.Start(path))
p.WaitForExit();
}
这种变体更糟,因为它不必要地阻塞了后台线程等待。