C# 如何异步httpwebrequest和线程
我尝试异步httpwebrequest三天,我尝试了所有的事情,首先我的代码是C# 如何异步httpwebrequest和线程,c#,C#,我尝试异步httpwebrequest三天,我尝试了所有的事情,首先我的代码是 HttpWebRequest httpWebRequest0_1 = (HttpWebRequest)WebRequest.Create("dir.com" + "/access_token.json"); httpWebRequest0_1.AllowAutoRedirect = true; httpWebRequest0_1.KeepAlive = true; httpWebRequest0_1.UseDefau
HttpWebRequest httpWebRequest0_1 = (HttpWebRequest)WebRequest.Create("dir.com" + "/access_token.json");
httpWebRequest0_1.AllowAutoRedirect = true;
httpWebRequest0_1.KeepAlive = true;
httpWebRequest0_1.UseDefaultCredentials = true;
httpWebRequest0_1.Headers.Add(this.string_6, string_5);
我希望每次都发送异步请求,但我的CPU和RAM使用率为100%,异步方法为
Enumerable.Range(0, 5).ToList().ForEach(f =>
{
new Thread(() =>
{
method_6();
Thread.sleep(1000);
}).Start();
});
我希望每次发送一秒钟的请求。由于所讨论的代码片段有限,我建议使用TAP,如下所示:
async Task RequestAsync()
{
for ( int i = 0; i < 5; i++ )
{
await method_6();
await Task.Delay(TimeSpan.FromSeconds(1));
}
}
将睡眠放在foreach部分,而不是线程的一部分此块我的UI然后不要在UI上运行该函数然后Backgroundworker好的选择?“Backgroundworker好的选择”不。使用Task/async/await。
async Task method_6()
{
// Create WebRequest httpWebRequest0_1 like in question
await httpWebRequest0_1.GetResponseAsync();
}