2011-03-26 166 views
0

我有这样的代码:是否可以“加入”DownloadStringAsync操作?

public static String Download(string address) { 
    WebClient client = new WebClient(); 
    Uri uri = new Uri(address); 

    // Specify a progress notification handler. 
    client.DownloadProgressChanged += (_sender, _e) => { 
     // 
    }; 

    // ToDo: DownloadStringCompleted event 

    client.DownloadStringAsync(uri); 
} 

而不必我的代码的其余部分的执行在DownloadStringCompleted事件处理程序的下载完成后,我可以采用某种Join这个异步请求?它将被安置在另一个线程中(这样做,以便我可以访问下载进度)。我知道DownloadStringAsync可以采取第二个参数;手册中称为userToken的对象。这可以用吗?谢谢,

回答

2

你可以使用一个manual reset event

class Program 
{ 
    static ManualResetEvent _manualReset = new ManualResetEvent(false); 

    static void Main() 
    { 
     WebClient client = new WebClient(); 
     Uri uri = new Uri("http://www.google.com"); 

     client.DownloadProgressChanged += (_sender, _e) => 
     { 
      // 
     }; 

     client.DownloadStringCompleted += (_sender, _e) => 
     { 
      if (_e.Error == null) 
      { 
       // do something with the results 
       Console.WriteLine(_e.Result); 
      } 
      // signal the event 
      _manualReset.Set(); 
     }; 

     // start the asynchronous operation 
     client.DownloadStringAsync(uri); 

     // block the main thread until the event is signaled 
     // or until 30 seconds have passed and then unblock 
     if (!_manualReset.WaitOne(TimeSpan.FromSeconds(30))) 
     { 
      // timed out ... 
     } 
    } 
} 
+0

完美,谢谢! – 2011-03-26 17:21:45

+0

您的修改更加完美,因为我希望在一段时间后请求超时。再次感谢!! – 2011-03-26 17:27:31

1

我的第一个想法是使用DownloadString,同步版本DownloadStringAsync。但是,您似乎必须使用异步方法来获取进度通知。好的,这没什么大不了的。只需订阅DownloadStringCompleted并使用一个简单的等待句柄(如ManualResetEventSlim)阻止,直到它完成。

有一点需要注意的是,我不确定是否对DownloadStringAsync甚至提出了进度通知。根据MSDN,DownloadProgressChanged与一些异步方法相关联,但不是DownloadStringAsync

+0

“......做这种方式让我有机会获得下载进度......” – 2011-03-26 17:15:45

+0

@SimpleCoder:是啊,我意识到自己的天真的答案是错后我发布了......现在修好了,我希望! – bobbymcr 2011-03-26 17:19:46

+0

没问题,谢谢你的答案!我刚刚尝试了达林季米特洛夫的代码,事件确实引发了。 – 2011-03-26 17:22:28

相关问题