简体   繁体   English

为什么我的异步回调在同一线程中运行?

[英]Why is my async callback running in the same thread?

I'm trying to use the FtpWebRequest async calls ( BeginGetResponse / EndGetResponse ). 我正在尝试使用FtpWebRequest异步调用( BeginGetResponse / EndGetResponse )。

However, it appears that the callback from BeginGetResponse is running in the same thread as my application, when I was under the impression it would use a different (and thread pool) thread. 但是,似乎来自BeginGetResponse的回调在与我的应用程序相同的线程中运行,当给我印象时,它将使用不同的(和线程池)线程。 This means my application blocks inside the callback before continuing. 这意味着我的应用程序在继续之前在回调内部阻塞。

I've setup a LINQPad proof-of-concept as follows: 我已经设置了LINQPad概念验证,如下所示:

"Starting".Dump();
Thread.CurrentThread.GetHashCode().Dump(); 
Thread.CurrentThread.IsThreadPoolThread.Dump();

IAsyncResult result = request.BeginGetResponse((ar) => 
{
     "Inside Callback".Dump();
     Thread.CurrentThread.GetHashCode().Dump();
     Thread.CurrentThread.IsThreadPoolThread.Dump();
     var resp = request.EndGetResponse(ar);
     "Callback Complete".Dump();
}, null);

"After Callback".Dump();

This prints output as follows: 打印输出如下:

Starting
33
False
Inside Callback
33
False
Callback Complete
After Callback

What I would expect is something like this (assuming the callback took long enough to run): 我期望的是这样的事情(假设回调花费了足够长的时间才能运行):

Starting
33
False
Inside Callback
44
True
After Callback // App continues despite callback running
Callback Complete

With the callback running on the same application thread it means if something inside the callback takes a long time (eg introducing a Thread.Sleep for argument's sake), my application blocks there. 在同一应用程序线程上运行回调的情况下,这意味着如果回调中的内容花费很长时间(例如,为参数而引入Thread.Sleep ),我的应用程序将在那里阻塞。 This means I cannot setup a timeout on the request (eg with a ThreadPool.RegisterWaitForSingleObject ). 这意味着我无法在请求上设置超时(例如,使用ThreadPool.RegisterWaitForSingleObject )。

Am I missing something here? 我在这里想念什么吗?

当可以通过BeginXXX方法立即完成异步操作时,它不会在线程池线程上运行回调,而是将IAsyncResult.CompletedSynchronously属性设置true并同步执行回调。

我假设BeginGetResponse方法在调用者线程的上下文中调用回调

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM