VS11中的WebClient.DownloadStringTaskAsync(Uri,CancellationToken)在哪里

时间:2012-03-17 00:34:27

标签: c# async-ctp visual-studio-2012

在Async CTP中,有一个带签名的扩展方法

WebClient.DownloadStringTaskAsync(Uri,CancellationToken) 

VS11在哪里?
我是否需要安装Async CTP才能获得此方法?

4 个答案:

答案 0 :(得分:3)

在.NET 4.5中,您可能会使用新的HttpClient Class,尤其是GetStringAsync Method

答案 1 :(得分:2)

遗憾的是,内置了CancellationToken支持,但是这里可以通过利用Register和CancelAsync方法来近似它:

var downloadTask = webClient.DownloadStringTaskAsync(source);

string text;
using (cancellationToken.Register(() => webClient.CancelAsync()))
{
    text = await downloadTask;
}

答案 2 :(得分:1)

它仍然存在于.Net 4.5测试版中,请参阅MSDN,但它不再是扩展方法。

您可能指的是:WebClient未包含在.Net中用于Metro风格的应用程序。在那里,您应该使用HttpClient。另一种选择是使用HttpWebRequest,它仍然存在并且已经使用基于Task的异步方法进行了扩展。

答案 3 :(得分:0)

System.Net.WebClient和System.Net.Http.HttpClient这两个类都有一个异步函数。这使您可以创建异步功能。当GetStringAsync函数异步运行时,您可以定期检查是否请求取消。

实施例:     使用System.Net.Http;     类HttpSonnetFetcher     {         const string sonnetsShakespeare = @“http://www.gutenberg.org/cache/epub/1041/pg1041.txt”;

    public async Task<IEnumerable<string>> Fetch(CancellationToken token)
    {
        string bookShakespeareSonnets = null;
        using (var downloader = new HttpClient())
        {
            var downloadTask = downloader.GetStringAsync(sonnetsShakespeare);
            // wait until downloadTask finished, but regularly check if cancellation requested:
            while (!downloadTask.Wait(TimeSpan.FromSeconds(0.2)))
            {
                token.ThrowIfCancellationRequested();
            }
            // if still here: downloadTask completed
            bookShakespeareSonnets = downloadTask.Result;
        }

        // just for fun: find a nice sonnet, remove the beginning, split into lines and return 12 lines
        var indexNiceSonnet = bookShakespeareSonnets.IndexOf("Shall I compare thee to a summer's day?");
        return bookShakespeareSonnets.Remove(0, indexNiceSonnet)
            .Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)
            .Take(12);  
    }
}

用法如下:

private void TestCancellationHttpClient()
{
    try
    {
        var sonnetFetcher = new HttpSonnetFetcher();
        var cancellationTokenSource = new CancellationTokenSource();

        var sonnetTask = Task.Run(() => sonnetFetcher.Fetch(cancellationTokenSource.Token));
        cancellationTokenSource.CancelAfter(TimeSpan.FromSeconds(10));

        // meanwhile do something else, checking regularly if the task finished, or if you have nothing to do, just Task.Wait():
        while (!sonnetTask.Wait(TimeSpan.FromSeconds(0.25)))
        {
            Console.Write('.');
        }
        // if still here: the sonnet is fetched. return value is in sonnetTask.Result
        Console.WriteLine("A nice sonnet by William Shakespeare:");
        foreach (var line in sonnetTask.Result)
        {
            Console.WriteLine(line);
        }
    }

    catch (OperationCanceledException exc)
    {
        Console.WriteLine("Canceled " + exc.Message);
    }
    catch (AggregateException exc)
    {
        Console.WriteLine("Task reports exceptions");
        var x = exc.Flatten();
        foreach (var innerException in x.InnerExceptions)
        {
            Console.WriteLine(innerException.Message);
        }
    }
    catch (Exception exc)
    {
        Console.WriteLine("Exception: " + exc.Message);
    }
}

在一个简单的控制台程序中尝试这个,并看到正确获取十四行诗,从10秒开始减少取消,直到0.1秒,并看到任务被正确取消。

  

Nota Bene:虽然抛出了OperationCancelledException,但此异常被包装为AggregateException的内部异常。任务中发生的所有异常始终包含在AggregateException中。