silverlight中异步调用招致的缺陷
silverlight中异步调用导致的缺陷?
在silverlight中是无法阻塞UI线程的,所有得web调用都是异步的。
这样会遇到个问题:
当user更新UI中的一个控件A时会异步调用web method1.
然后user更新UI中的一个控件B时会异步调用web method2.
web method 1,2获得数据后会更新UI中的一个控件C。
此时由于异步,C的数据源就取决于web method1和web method2谁的数据量大返回的慢了。
这种情况是不是无解????
------解决方案--------------------
线程同步使用 ManualResetEvent 或者 AutoResetEvent。
例如
在silverlight中是无法阻塞UI线程的,所有得web调用都是异步的。
这样会遇到个问题:
当user更新UI中的一个控件A时会异步调用web method1.
然后user更新UI中的一个控件B时会异步调用web method2.
web method 1,2获得数据后会更新UI中的一个控件C。
此时由于异步,C的数据源就取决于web method1和web method2谁的数据量大返回的慢了。
这种情况是不是无解????
------解决方案--------------------
线程同步使用 ManualResetEvent 或者 AutoResetEvent。
例如
var eh1 = new ManualResetEvent(false);
var eh2 = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(h =>
{
var web = new WebClient();
web.DownloadStringCompleted += (s, e) =>
{
eh1.Set();
};
web.DownloadStringAsync(new Uri("http://www.google.com"));
});
ThreadPool.QueueUserWorkItem(h =>
{
var web = new WebClient();
web.DownloadStringCompleted += (s, e) =>
{
eh2.Set();
};
web.DownloadStringAsync(new Uri("http://bbs.****.net/topics/390742949"));
});
eh1.WaitOne();
eh2.WaitOne();
txt.Text = "两个访问都完成了。";