gpt4 book ai didi

c# - 我如何并行化这种模式?

转载 作者:太空宇宙 更新时间:2023-11-03 23:07:23 25 4
gpt4 key购买 nike

我想要的东西相当于

var docs = new LinkedList<string>();
for(int i = 0; ; ++i)
{
string html = client.DownloadString($"http://someforum.com/page?id={i}");
if(html == null)
break;
docs.AddLast(html);
}

除非那会利用 client.DownloadString($"http://someforum.com/page?id={i}"); 是一个长时间运行的任务在不同的线程中运行。

基本上,我要做的是从页面获取 HTML

"http://someforum.com/page?id=0", "http://someforum.com/page?id=1", . ..

除非我没有从 id=m 获得页面,否则我会承担任何尝试为某些 获取页面 id=n 的任务n>m 不会得到一个页面,可以关闭。

最佳答案

您打算并行化的程序以 IO 调用为主要方面,因此最好使用 TaskCompletionSource 进行异步编程,因为 DownloadAsync 方法Webclient 返回一个 void。以下是 ReadData 的修改版本:

public Task<string> ReadData(int i)
{
TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();
var client = new WebClient();
string uriString = @"http://someforum.com/page?id=" + i;
client.DownloadStringCompleted += (sender,args) =>
{
tcs.TrySetCanceled();
tcs.TrySetException(args.Error);
tcs.TrySetResult(args.Result);
};

client.DownloadStringAsync(new Uri(uriString));

return tcs.Task;
}

异步调用 ReadData

您最好通过 async 方法来完成,该方法可以 await,直到所有下载调用返回。此外,由于它的多个 Async 调用,因此最好将限制设置为 i,就像同步版本一样,您不能检查每个下载和返回的值,所有调用都在此一起处理案例

public async Task<LinkedList<string>> ReadDataAsync()
{
var docs = new LinkedList<string>();

List<Task<string>> taskList = new List<Task<string>>();

for (int i = 0; ; ++i) // Set a limit to i, since you are not running synchronously, so you cannot keep checking which value yields null as result
{
int localId = i;
taskList.Add(ReadData(localId));
}

await Task.WhenAll(taskList);

// Do Link List processing, if the Task is not cancelled and doesn't have an error, then result can be accessed
}

关于c# - 我如何并行化这种模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40700862/

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