事件处理程序返回后,变量 uiContext 会超出范围吗?编译器在幕后做了什么来使这段代码工作。
private void findButton_Click(object sender, RoutedEventArgs e)
{
SynchronizationContext uiContext = SynchronizationContext.Current;
Task.Factory.StartNew(() =>
{
string pictures =
Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
var folder = new DirectoryInfo(pictures);
FileInfo[] allFiles =
folder.GetFiles("*.jpg", SearchOption.AllDirectories);
FileInfo largest =
allFiles.OrderByDescending(f => f.Length).FirstOrDefault();
uiContext.Post(unusedArg =>
{
outputTextBox.Text = string.Format("Largest file ({0}MB) is {1}",
largest.Length / (1024 * 1024), largest.FullName);
},
null);
});
}