为什么这个异步示例在没有 Dispatcher 和 Control.BeginInvoke 的情况下也能工作?
我正在测试我在其他帖子中编写的异步示例,我对其进行了修改以在文本框中显示一些信息。接下来发生的事情是我没想到的。我不知道为什么它在从另一个线程修改控件时不抛出异常。我是瞎子还是为什么我看不到?
这是示例,它对于 silverlight 和 WinForms 的工作原理相同:
int rand=0;
public MainPage()
{
InitializeComponent();
}
public Func<Action<int, int>, Action<int>> DownloadDataInBackground = (callback) =>
{
return (c) =>
{
WebClient client = new WebClient();
Uri uri = new Uri(string.Format("https://www.google.com/search?q={0}", c));
client.DownloadStringCompleted += (s, e2) =>
{
callback(c, e2.Result.Length);
};
client.DownloadStringAsync(uri);
};
};
private void button1_Click(object sender, RoutedEventArgs e)
{
int callid = rand++;
Debug.WriteLine("Executing CallID #{0}", callid);
DownloadDataInBackground((c3, r3) =>this.textBox1.Text+=string.Format("The result for the callid {0} is {1} \n", c3, r3))(callid);
}
快速点击按钮,不会失败。
我们将非常感谢您的帮助。
编辑:添加的图片显示 Windows 窗体始终从主线程执行控件修改,但是,如果它应该是另一个线程,为什么呢?
I was testing an Asynchronous example I wrote in other post, I modified it to show some info in a textbox. what happened next I was not expecting. I don't know why it does not throw an exception when modifying a control from another thread. am I blind or why I don't see it?
here is the example, it works the same for silverlight and WinForms:
int rand=0;
public MainPage()
{
InitializeComponent();
}
public Func<Action<int, int>, Action<int>> DownloadDataInBackground = (callback) =>
{
return (c) =>
{
WebClient client = new WebClient();
Uri uri = new Uri(string.Format("https://www.google.com/search?q={0}", c));
client.DownloadStringCompleted += (s, e2) =>
{
callback(c, e2.Result.Length);
};
client.DownloadStringAsync(uri);
};
};
private void button1_Click(object sender, RoutedEventArgs e)
{
int callid = rand++;
Debug.WriteLine("Executing CallID #{0}", callid);
DownloadDataInBackground((c3, r3) =>this.textBox1.Text+=string.Format("The result for the callid {0} is {1} \n", c3, r3))(callid);
}
Tap the button pretty fast, it wont fail.
your help will be very appreciated.
Edit: added picture showing that windows forms always execute controls modification from the main thread, but, why if it is supposed to be another one?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么您的代码不会按照您期望的方式失败的实际答案是
WebClient
在 UI 线程上调用其事件。因此,您并没有像您想象的那样在不同的线程上修改您的控件。The actual answer to why your code doesn't fail in the way you expect it to is that the
WebClient
invokes its events on the UI thread. Hence you aren't modifying your control on a different thread as you seem to imagine you are.