gpt4 book ai didi

multithreading - ManualResetEvent.WaitOne 阻塞所有线程

转载 作者:行者123 更新时间:2023-12-04 06:36:58 24 4
gpt4 key购买 nike

我有以下代码

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() 不应该阻止他。

我需要的是创建一个同步方法而不是异步。

谢谢!

UPD:使用异步调用更新源代码。

最佳答案

client.DownloadString 是同步方法,所以你完成的处理程序永远不会被调用。需要调用异步版本:client.DownloadStringAsync()

您可以阅读有关 DownloadStringAsync 的更多信息在 msdn 上。如果您依赖于应该调用某些代码的事实,那么将代码放入 try-catch block 并处理异常也是明智的。

您的代码可能如下所示:

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();
}

关于multithreading - ManualResetEvent.WaitOne 阻塞所有线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9359084/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com