我对 STA 的理解是,如果我的线程在 STA 公寓中运行,那么我不必担心线程安全,并且对线程函数的调用会自动排队。
我的问题是,如果我在 STA 中启动一个工作线程,然后通过函数从该线程获取一个对象,那么在使用该对象时我是否需要担心线程安全?或者该对象上的函数调用是线程安全的吗?
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?
发布评论
评论(2)
STA 基本上与 COM 以及 COM 对象的处理方式有关。它不会自动保证正常.NET 代码中的安全。没有什么可以自动使您的 .NET 代码成为线程安全的。
假设您只是处理托管代码,我建议您忘记这些单元,因为它们不太可能与您编写线程安全代码的方式相关(或者实际上您是否想要使大多数内容相关)您的代码线程安全)。 (强制参考:Eric Lippert 的 “你所说的线程安全是什么?” 博客文章。)
STA is basically to do with COM, and how COM objects are handled. It doesn't automagically make things safe in normal .NET code. Nothing is going to automatically make your .NET code thread-safe.
Assuming you're just dealing with managed code, I suggest you forget about the apartments, as they're unlikely to be relevant to how you write thread-safe code (or indeed whether you want to make most of your code thread-safe). (Obligatory reference: Eric Lippert's "What is this thing you call thread safe?" blog post.)
将线程设置为 STA 线程并不会神奇地使任何事情变得安全。将线程标记为 STA 线程意味着需要在 STA 线程上运行的 COM 对象可以在该线程上运行。这样 COM 层就知道如何正确地编组调用。
有关简要介绍,请参阅:
http://blogs。 msdn.com/b/ericlippert/archive/2003/09/18/53041.aspx
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