0

My understanding of STA is that if my thread is running in an STA apartment then I do not have to worry about thread safety and calls to the functions of my thread are automagically queued.

My question is that if I start a worker thread in STA and then obtain an object from that thread via a function, do I have to worry about thread safety when using that object? Or are function calls on that object thread-safe?

4

2 回答 2

2

Making a thread an STA thread does not magically make anything safe. Marking a thread as an STA thread means that COM objects which are required to run on an STA thread can be run on that thread. It's so that the COM layer knows how to marshal calls appropriately.

For a brief introduction, see:

http://blogs.msdn.com/b/ericlippert/archive/2003/09/18/53041.aspx

于 2011-02-25T15:25:03.850 回答
2

STA 基本上与 COM 相关,以及如何处理 COM 对象。它不会自动使正常 .NET 代码中的事情变得安全。没有什么可以自动使您的 .NET 代码成为线程安全的。

假设您只是在处理托管代码,我建议您忘记公寓,因为它们不太可能与您编写线程安全代码的方式相关(或者实际上您是否想让大部分代码线程安全) . (必读:Eric Lippert 的“你称之为线程安全的东西是什么?”博文。)

于 2011-02-25T13:26:48.297 回答