以下是关于两个示例的基本代码:
private void AsyncTest()
{
//GetServiceObject Will add custom bindings and more..
Client client = ClientBuilder.GetServiceObject();
while (true)
{
Semaphore semaphore = new Semaphore(0,1);
client.BeginTest(BeginTestCallback, new AsyncState
{
Client = client,
Semaphore = semaphore
});
semaphore.WaitOne();
}
}
private void BeginTestCallback(IAsyncResult asyncResult)
{
try
{
AsyncState state = asyncResult.AsyncState as AsyncState;
Client client = state.Client;
Semaphore semaphore = state.Semaphore;
Client.EndTest(asyncResult);
semaphore.Release();
}
catch (Exception e)
{
//Will catch the exception here because of Client.EndTest(asyncResult) in the first example
Debug.Assert(false, e.Message);
}
}
我们知道回调是在.net Threadpool的一个线程中调用的。
如果我以这种方式调用AsyncTest():
Task.Factory.StartNew(() => AsyncTest());
这意味着AsyncTest将在.net Threadpool的一个线程中运行。 在这种情况下,一切都将按预期工作,无一例外。
但是,如果我以这种方式启动一个线程:
ThreadStart ts = new ThreadStart(() => AsyncTest());
Thread t = new Thread(ts);
t.Start();
即使我把它放在10分钟,它也会对“SendTimeout”进行随机TimeoutException。当我检查wireshark时,它将随机地从我甚至看不到Syn,我们只发送soap标头并关闭连接(仅当它超时)。
请注意,我正在运行10个线程,每秒执行30个请求。第二个例子可能需要一分钟才能失败。
为什么?