AutoResetEvent配合webClient.DownloadDataAsync 接收不到信号问题

erictang2003 2013-12-19 05:09:33
就是很简单的从书上抄下来的,放在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(); //
//

}
}
...全文
197 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
erictang2003 2014-01-22
  • 打赏
  • 举报
回复
经过跟踪,发现如果 webClient.DownloadDataAsync(new Uri(imgUrl)); downloadWaitEvent.WaitOne(10000) 这样写,实际webClient 仍然是使用和downloadWaitEvent.WaitOne 同一个线程,因此造成阻塞,实际异步下载没有执行。 ThreadPool.QueueUserWorkItem((state)=> { webClient.DownloadDataAsync(new Uri(imgUrl)); }, null); downloadWaitEvent.WaitOne(10000) 这样写就强制线程池给webClient.DownloadDataAsync 分配了另一个线程。
Bonjour-你好 2013-12-19
  • 打赏
  • 举报
回复
    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));
        }
    }

8,756

社区成员

发帖
与我相关
我的任务
社区描述
WPF/Silverlight相关讨论
社区管理员
  • WPF/Silverlight社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧