gpt4 book ai didi

c# - 是否可以保证 AsyncCallbacks 始终在主线程上执行?

转载 作者:太空宇宙 更新时间:2023-11-03 21:17:53 24 4
gpt4 key购买 nike

正是问题所说的。

我已阅读给定 here 的 MSDN 文章,并且(除非我是盲人),看不到任何明确证实这一点的地方。

为了提供更多范围,我主要指的是 Socket 类中提供的 Socket.Beginxxx 方法。

我可以假设任何 AsyncCallbacks 都将在主线程中执行吗?假设我调用的任何 Socket.Beginxxx 方法也将从主线程调用。

编辑:如果不是这种情况,当我在 Socket.Beginxxx AsyncCallbacks 之一中修改包含类的私有(private)成员时,我是否应该锁定它们?例如。向字典中添加一个项目?

最佳答案

I've read the MSDN article given here, and (unless I'm blind), can't see anywhere where it explicity confirms this.

相关引述是(强调):

Use an AsyncCallback delegate to process the results of an asynchronous operation in a separate thread.

回调保证在原始线程中执行;事实上,它保证在另一个线程(即线程池线程)上运行。

尽管有其他答案,但这与 SynchronizationContextTAP 完全无关。或 EAP与他们的上下文一起工作。 AsyncCallbackAPM 的一部分- 最古老的异步模式 - 绝对不会为您进行自动线程编码(marshal)处理。

If this is not the case, should I lock private members of the containing class when I modify them in one of the Socket.Beginxxx AsyncCallbacks? E.g. adding an item to a dictionary?

你可以。我发现在我的异步套接字代码中,将所有回调编码回单个共享线程更容易,该线程负责所有套接字操作和相关数据。然后不需要锁,因为所有“已完成的事件”都同步到单个线程。

关于c# - 是否可以保证 AsyncCallbacks 始终在主线程上执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32813414/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com