【发布时间】:2014-06-09 04:46:39
【问题描述】:
我的理解是,如果我使用异步,线程会发出 Web 请求并继续前进。当响应返回时,另一个线程会从那里获取它。因此,闲置的绑定线程数量较少。 这不是意味着最大活动线程数会下降吗?但在下面的示例中,不使用异步的代码最终会使用较少数量的线程。谁能解释一下原因?
没有异步的代码(使用较少的线程):
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Threading;
namespace NoAsync
{
internal class Program
{
private const int totalCalls = 100;
private static void Main(string[] args)
{
for (int i = 1; i <= totalCalls; i++)
{
ThreadPool.QueueUserWorkItem(GoogleSearch, i);
}
Thread.Sleep(100000);
}
private static void GoogleSearch(object searchTerm)
{
Thread.CurrentThread.IsBackground = false;
string url = @"https://www.google.com/search?q=" + searchTerm;
Console.WriteLine("Total number of threads in use={0}", Process.GetCurrentProcess().Threads.Count);
WebRequest wr = WebRequest.Create(url);
var httpWebResponse = (HttpWebResponse) wr.GetResponse();
var reader = new StreamReader(httpWebResponse.GetResponseStream());
string responseFromServer = reader.ReadToEnd();
//Console.WriteLine(responseFromServer); // Display the content.
httpWebResponse.Close();
Console.WriteLine("Total number of threads in use={0}", Process.GetCurrentProcess().Threads.Count);
}
}
}
异步代码(使用更多线程)
using System;
using System.Diagnostics;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
namespace AsyncAwait
{
internal class Program
{
private const int totalCalls = 100;
private static DateTime start = System.DateTime.Now;
private static void Main(string[] args)
{
var tasks = new List<Task>();
for (int i = 1; i <= totalCalls; i++)
{
var searchTerm = i;
var t = GoogleSearch(searchTerm);
tasks.Add(t);
}
Task.WaitAll(tasks.ToArray());
Console.WriteLine("Hit Enter to exit");
Console.ReadLine();
}
private static async Task GoogleSearch(object searchTerm)
{
Thread.CurrentThread.IsBackground = false;
string url = @"https://www.google.com/search?q=" + searchTerm;
Console.WriteLine("Total number of threads in use={0}", Process.GetCurrentProcess().Threads.Count);
using (var client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(url))
{
HttpContent content = response.Content;
content.Dispose();
Console.WriteLine("Total number of threads in use={0}", Process.GetCurrentProcess().Threads.Count);
Console.WriteLine("TimeSpan consumed {0}", System.DateTime.Now.Subtract(start));
}
}
}
}
}
我明白我的结果包括非托管线程。但是总线程数不应该还少吗?
更新:我用 Noseratio 提供的代码更新了异步调用
【问题讨论】:
-
我认为通过调用
Task.Start(),您正在启动新线程。相反,将GoogleSearch()更改为返回Task而不是void... 在Main()中,只需等待它而不是启动另一个无用的任务。
标签: c# async-await c#-5.0