AsyncCallBack 同步完成 [英] AsyncCallBack CompletedSynchronously

查看:10
本文介绍了AsyncCallBack 同步完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近注意到以下模式,但我并不完全掌握 CompletedSynchronously 属性的用法:

I've noticed the following pattern recently, but I don't entirely grasp the usage of the CompletedSynchronously property:

IAsyncResult channelOpenResult = channel.BeginOpen(new AsyncCallback(OnOpenCompleteChannel), channel);
if (channelOpenResult.CompletedSynchronously)  
{  
    CompleteOpenChannel(channelOpenResult);  
}

然后,在回调中:

void OnOpenCompleteChannel(IAsyncResult result)  
{  
    if (result.CompletedSynchronously)  
        return;  
    else  
        CompleteOpenChannel(result);  
}

在代码中的某处当然有一个函数:

And somewhere in the code there is of course a function:

void CompleteOpenChannel(IAsyncResult result) ...

这是一种根据异步调用是否直接完成而对异步调用进行不同处理的方法?但是为什么在这种情况下使用它,因为 AsyncCallback 总是会被调用(会吗?)?有人可以举一个同步进行调用的例子吗?

Is this a way to handle the asynchronous call differently depending on whether it completes directly or not? But why use it in this case, since the AsyncCallback always will be called (will it?)? Could someone give an example where the call is made synchronously?

推荐答案

参见 这个博客.一个常见的模式在循环中执行异步工作,检查 CompletedSynchronously 有助于避免出现不走运"和一堆异步调用碰巧完成同步的情况,并且您可能面临 StackOverflowException 的风险.(例如,如果您正在通过网络读取数据,并且您正在读取的数据已经通过线路传输并被缓冲,则您的异步调用可能会同步完成,这意味着您的回调是在同一线程上调用的(具有更高的堆栈),这意味着您最好不要在循环中安排另一个异步调用.)

See this blog. A common pattern does async work in a loop, and checking CompletedSynchronously helps avoid the case where you get 'unlucky' and a bunch of async calls happen to complete sync and you risk StackOverflowException. (E.g. if you're reading data over the network, and the data you're reading has already come over the wire and is buffered, your async call may complete synchronously, which means your callback is called on the same thread (with a taller stack), which means you better not schedule another async call in a loop.)

这篇关于AsyncCallBack 同步完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆