2011-05-26 49 views
0

我需要這個代碼DispatcherTimer和WebClient.DownloadStringAsync拋出「Web客戶端不支持併發I/O操作的」異常

WebClient client = new WebClient(); 
    string url = "http://someUrl.com" 

    DispatcherTimer timer = new DispatcherTimer(); 
       timer.Interval = TimeSpan.FromSeconds(Convert.ToDouble(18.0)); 
       timer.Start(); 

       timer.Tick += new EventHandler(delegate(object p, EventArgs a) 
       { 
        client.DownloadStringAsync(new Uri(url)); 

        //throw: 
        //WebClient does not support concurrent I/O operations. 
       }); 

       client.DownloadStringCompleted += (s, ea) => 
       { 
        //Do something 
       }; 

回答

1

您使用的是共享WebClient實例和定時器幫助顯然造成超過一次下載一次。每次在Tick處理程序中啓動一個新的客戶端實例,或者禁用該計時器,以便在處理當前下載時不會再次打勾。

timer.Tick += new EventHandler(delegate(object p, EventArgs a) 
{ 
    // Disable the timer so there won't be another tick causing an overlapped request 
    timer.IsEnabled = false; 

    client.DownloadStringAsync(new Uri(url));      
}); 

client.DownloadStringCompleted += (s, ea) => 
{ 
    // Re-enable the timer 
    timer.IsEnabled = true; 

    //Do something     
}; 
+0

謝謝它適合我! – christiangobo 2011-05-26 18:45:03

相關問題