的AsyncCallback CompletedSynchronously [英] AsyncCallBack CompletedSynchronously

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

问题描述

我已经注意到了以下模式最近,但我并不完全掌握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);  
}

和话又说回来,在回调:

And then again, in the callback:

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

和地方在code当然还有一个功能:

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 CompletedSynchronously的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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