我有以下代码

ThreadPool.QueueUserWorkItem(new WaitCallback(DownloadAsync), apiMethod);
downloadHandle.WaitOne();

DownloadAsync在哪里
private void DownloadAsync(object _uri)
        {
            var url = _uri as string;
            WebClient client = new WebClient();
            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
            client.DownloadStringAsync(new Uri(GLOBALS.MAIN_API_URL + url, UriKind.Absolute));
        }

void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            result = e.Result;
            downloadHandle.Set();
        }

所以我的问题是,将永远不会调用downloadHandle.Set()。但是我不明白为什么?我为DownloadAsync创建了一个新线程,并且downloadHandle.WaitOne()不应阻止他。

我需要的是创建一个Sync方法而不是Async。

谢谢!

UPD:通过异步调用更新了源代码。

最佳答案

client.DownloadString是同步方法,因此永远不会调用您完成的处理程序。您需要调用异步版本:client.DownloadStringAsync()
您可以在msdn上阅读有关DownloadStringAsync的更多信息。将代码放在try-catch块中并处理异常(如果您依赖于应该调用某些代码的事实)也是明智的。

您的代码可能如下所示:

private void DownloadAsync(object _uri)
{
    try
    {
        var url = _uri as string;
        WebClient client = new WebClient();
        client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
        client.DownloadStringAsync(new Uri(GLOBALS.MAIN_API_URL + url, UriKind.Absolute));
    }
    catch //appropriate exception
    {
       //Handle exception (maybe set downloadHandle or report an error)
    }
}

void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    result = e.Result;
    downloadHandle.Set();
}

10-08 09:46