开发者

Is it possible to "join" a DownloadStringAsync operation?

I have this code:

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(u开发者_JAVA百科ri);
}

Instead of having the rest of my code execute in the DownloadStringCompleted event handler when the download is complete, can I somehow Join this Async request? It will be housed in another thread (doing it this way so I have access to the download progress). I know that DownloadStringAsync can take a second parameter; an object called userToken in the manual. Could this be of use? Thank you,


You could use a 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 ...
        }
    }
}


My first thought would be to use DownloadString, the synchronous version of DownloadStringAsync. However, it seems that you must use an async method to get the progress notification. Okay, that's no big deal. Just subscribe to DownloadStringCompleted and use a simple wait handle like ManualResetEventSlim to block until it completes.

One note, I am not sure if the progress notification is even raised for DownloadStringAsync. According to MSDN, DownloadProgressChanged is associated with some of the async methods, but not DownloadStringAsync.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜