读书人

AutoResetEvent配合webClient.Downloa

发布时间: 2014-01-22 14:50:12 作者: rapoo

AutoResetEvent配合webClient.DownloadDataAsync 接收不到信号问题
就是很简单的从书上抄下来的,放在wpf的 MainWindow 中测试,但是发现AutoResetEvent 接收不到 .Set() 信号,永远都是超时webClient.CancelAsync() 的情况,求测试求解答。

public MainWindow()
{
InitializeComponent();

///////////////////////////////////////////////////////

AutoResetEvent downloadWaitEvent = new AutoResetEvent(false);
WebClient webClient = new WebClient();

webClient.DownloadDataCompleted += new DownloadDataCompletedEventHandler(rr);


var imgUrl = "http://img4.cache.netease.com/m/2013/12/18/20131218104403bd5df.png";//

//
webClient.DownloadDataAsync(new Uri(imgUrl), downloadWaitEvent);

if (downloadWaitEvent.WaitOne(10000)) //
{
//
System.Windows.MessageBox.Show("ll");
//
}
else
{
webClient.CancelAsync();
System.Windows.MessageBox.Show("CancelAsync");
}
}

private void rr(object sender, DownloadDataCompletedEventArgs e)
{
//
var waiterTmp = (AutoResetEvent)e.UserState;
//
try
{
//
if (!e.Cancelled && e.Error == null)
{
var bytes = e.Result;
//
}
}
finally
{
//
waiterTmp.Set(); //
//

}
}
[解决办法]

    public partial class MainWindow : Window
{
public MainWindow()
{


InitializeComponent();
}

private void Button_Click(object sender, RoutedEventArgs e)
{
AutoResetEvent downloadWaitEvent = new AutoResetEvent(false);
ThreadPool.QueueUserWorkItem(new WaitCallback(WorkMethod), downloadWaitEvent);

if (downloadWaitEvent.WaitOne(10000)) {
MessageBox.Show("AutoResetEvent-OK!");
} else {
MessageBox.Show("AutoResetEvent-Bad!");
}
}

private void WorkMethod(object stateInfo)
{
WebClient webClient = new WebClient();
webClient.DownloadDataCompleted += (s, e) => {
try {
if (!e.Cancelled && e.Error == null) {
}
} finally {
((AutoResetEvent)stateInfo).Set();
}
};
var imgUrl = "http://img4.cache.netease.com/m/2013/12/18/20131218104403bd5df.png";
webClient.DownloadDataAsync(new Uri(imgUrl));
}
}

读书人网 >CAD教程

热点推荐