首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 媒体动画 > CAD教程 >

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

2014-01-22 来源:读书人网 【读书人网(Reader8.cn):综合教育门户网站】
AutoResetEvent配合webClient.DownloadDataAsync 接收不到信号问题就是很简单的从书上抄下来的,放在wpf的

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));
        }
    }