是否可以“加入”DownloadStringAsync操作?

时间:2011-03-26 17:12:21

标签: c# .net multithreading

我有这段代码:

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事件处理程序中执行其余代码,而不是{@ 1}}这个异步请求吗?它将被放置在另一个线程中(这样做,因此我可以访问下载进度)。我知道Join可以采取第二个参数;手册中名为DownloadStringAsync的对象。这可能有用吗?谢谢,

2 个答案:

答案 0 :(得分: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 ...
        }
    }
}

答案 1 :(得分:1)

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

一个注意事项,我不确定是否为DownloadStringAsync提出了进度通知。根据MSDN,ManualResetEventSlim与某些异步方法相关联,但不与{{1}}相关联。

相关问题