我的理解是,如果我使用异步,线程会发出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 = …Run Code Online (Sandbox Code Playgroud) (我正在使用.Net 4.0)
我想从我的服务层异步调用WCF服务.此服务层由MVC.Net控制器使用.我已经读过,异步调用WCF服务是一种很好的做法.所以我正在使用begin/end(apm).我想仔细检查我是否做得很丰富:
public byte[] GetSomeData()
{
IAsyncResult result = myServiceClient.BeginDoSomething(someInputValue, null, null);
var data = _pdfCreatieService.EndCreateForPreview(result);
return data;
}
Run Code Online (Sandbox Code Playgroud)
我不完全确定上面的代码,因为我已经看到了类似下面代码的构造,在我的情况下看起来有点复杂和不必要:
public byte[] GetSomeData()
{
var myState = new MyState();
IAsyncResult result = _myServiceClient.BeginDoSomething(someInputValue, CreateForPreviewCallback, myState);
result.AsyncWaitHandle.WaitOne();
return myState.Bytes;
}
private void DoSomethingCallback(IAsyncResult result)
{
var myState = (MyState)result.AsyncState;
myState.Bytes = _myServiceClient.EndDoSomething(result);
}
Run Code Online (Sandbox Code Playgroud)
感谢Avner Shahar-Kashtan,Ned Stoyanov和Noseratio.你的答案非常有见地!