我正在尝试使用DownloadStringAsync下载一些HTML源代码。我的代码如下所示:

    WebClient client = new WebClient();

    client.DownloadStringCompleted +=
    new DownloadStringCompletedEventHandler(DownloadStringCallback2);
    client.DownloadStringAsync(new Uri(url));

private void DownloadStringCallback2(Object sender, DownloadStringCompletedEventArgs e)
{
    source = (string)e.Result;
    if (!source.Contains("<!-- Inline markers start rendering here. -->"))
        MessageBox.Show("Nope");
    else
        MessageBox.Show("Worked");
}

如果查看变量“源”,我可以看到其中有一些源,但不是全部。但是,如果我这样做是可行的:
while (true)
        {
            source = wb.DownloadString(url);
            if (source.Contains("<!-- Inline markers start rendering here. -->"))
                break;
        }

不幸的是,由于WP8没有DownloadString,所以我无法使用该方法。

有谁知道如何解决此问题,或者是否有更好的方法?

最佳答案

此功能应该可以帮助您

    public static Task<string> DownloadString(Uri url)
    {
        var tcs = new TaskCompletionSource<string>();
        var wc = new WebClient();
        wc.DownloadStringCompleted += (s, e) =>
        {
            if (e.Error != null) tcs.TrySetException(e.Error);
            else if (e.Cancelled) tcs.TrySetCanceled();
            else tcs.TrySetResult(e.Result);
        };
        wc.DownloadStringAsync(url);
        return tcs.Task;
    }

10-02 13:28