Skip to main content
 首页 » 编程设计

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

2024年02月05日10JustinYoung

正是问题所说的。

我已阅读给定 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.

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

尽管有其他答案,但这与 SynchronizationContext 或 TAP 完全无关。或 EAP与他们的上下文一起工作。 AsyncCallback 是 APM 的一部分- 最古老的异步模式 - 绝对不会为您进行自动线程编码(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?

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