TaskCompletionSource抛出错误但不确定原因

时间:2013-09-23 23:20:47

标签: c# webclient

    public static Task<string> GetData(string url, string data)
    {
        UriBuilder fullUri = new UriBuilder(url);

        if (!string.IsNullOrEmpty(data))
            fullUri.Query = data;

        WebClient client = new WebClient();

        var tcs = new TaskCompletionSource<string>();

        client.DownloadStringCompleted += (s, args) =>
        {
            if (args.Error != null)
                tcs.TrySetException(args.Error); // HERE
            else if (args.Cancelled)
                tcs.TrySetCanceled();
            else
                tcs.TrySetResult(args.Result);
        };

        client.DownloadStringAsync(fullUri.Uri);

        return tcs.Task;
    }

上述方法在“// Here”...

处出现错误

enter image description here

事情是,我相信URL和参数是正确的。除了创建我自己的API页面之外,我应该首先检查一些典型的东西吗?

1 个答案:

答案 0 :(得分:0)

首先,你可以使用WebClient.DownloadStringTaskAsync而不是自己的方法。

话虽如此,例外只是从WebClient返回的异常。 InnerException非常明确 - 服务器返回NotFound(即:404错误代码)。设置异常的代码看起来完全有效。