gpt4 book ai didi

C# Task Parallel Library 第一次慢

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

尝试并行执行多个 HTTP Get 请求,每个任务一个。如果我通过 Internet Explorer 执行 Gets,它们几乎会立即返回,但是当通过任务调用代码时,我第一次启动它们时它们会花几秒钟时间返回,但第二次运行它们会如我所料返回。所以要么我正在做一些阻塞的事情,要么由于某种原因线程没有启动?这是我第一次尝试使用 TPL。

这是基本的查找类:

public class Lookup
{
public string Name { get; set; }
public string URL { get; set; }

public Lookup(string Name, string URL)
{
this.Name = Name;
this.URL = URL;
}

public LookupReturn DoLookup()
{
LookupReturn d = new LookupReturn();
d.Name = this.Name;
d.URL = this.URL;

WebRequest wrGETURL;
wrGETURL = WebRequest.Create(this.URL);

Stream objStream;
objStream = wrGETURL.GetResponse().GetResponseStream();

StreamReader objReader = new StreamReader(objStream);

string sLine = objReader.ReadToEnd();
d.Result = sLine;
return d;
}
}

返回类型很简单:

public class LookupReturn
{
public string Name { get; set; }
public string Result { get; set; }
public string URL { get; set; }
}

因此尝试并行运行它 - 我是从 Winforms GUI 进行测试,但最终将在 WCF 服务中进行。

public partial class Form1 : Form
{
private List<Lookup> Lookups = new List<Lookup>();

private async void btnRunLookups_Click(object sender, EventArgs e)
{
Lookups.Add(new Lookup("Name1", "http://geturl1 "));
Lookups.Add(new Lookup("Name2", "http://geturl2 "));
// More lookups…

int workerThreads, complete;
ThreadPool.GetMinThreads(out workerThreads, out complete);

ThreadPool.SetMinThreads(100, complete);

btnRunLookups.Visible = false;
List <Task<LookupReturn>> lookupTasks = new List<Task<LookupReturn>>();
foreach(Lookup dl in Lookups)
{
lbLookups.Items.Add("Starting task for " + dl.URL);

Task<LookupReturn> t = new Task<LookupReturn>(() => dl.DoLookup() );
lookupTasks.Add(t);
t.Start();
}

//await Task.WhenAny(
// Task.WhenAll(lookupTasks.ToArray<Task<LookupReturn>>()),
// Task.Delay(3000)
// );

// This takes a good few seconds the first time
await Task.WhenAll(lookupTasks.ToArray<Task<LookupReturn>>());

// Now I need to see which ones completed and returned a result
foreach (var x in lookupTasks)
{
if (x.IsCompleted)
{
lbLookups.Items.Add(x.Result);
}
else
{
// lbLookups.Items.Add("Not finished " + x.Result.Name);
}
}
btnRunLookups.Visible = true;
}

最佳答案

Other people注意到 HttpWebRequest 的第一个请求可能需要很长时间,因为它正在寻找代理信息。尝试将其 Proxy 属性设置为 null。

wrGETURL = WebRequest.Create(this.URL);
wrGETURL.Proxy = null;

关于C# Task Parallel Library 第一次慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29236895/

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