我正在浏览Bart De Smet的C#5.0 Unleashed书中的一些代码,并使用进行了研究WebClient
。
在下面的代码中,我注意到回调是在UI线程上执行的。我知道WebClient.DownloadStringAsync
EAP的实现会捕获current SynchronizationContext
,并且一直在徘徊是否所有EAP的实现都在执行此操作,因为似乎无法指定SynchronizationContext
执行回调的方式。
这是有问题的代码:
private void loadButton_Click(object sender, EventArgs e)
{
var client = new WebClient();
client.DownloadStringCompleted += (o, args) =>
{
if (args.Error != null)
{
try
{
throw args.Error; // simply to restore structured exception handling?!
}
catch (WebException)
{
this.textBox.Text = "ERROR: " + args.Error.Message;
}
return;
}
// Already on the UI thread!
this.textBox.Text = args.Result;
};
client.DownloadStringAsync(new Uri(@"http:\\www.rpmglobal.com"));
}
不,绝对不是。当您WebClient's
执行最终会触发事件通知您的调用时,实现确实会嗅探当前电流SynchronizationContext
(例如DownloadStringAsync
),但这纯粹是实现特定的,而不是EAP的保证。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句