开发者

STA applies to objects and functions?

开发者 https://www.devze.com 2023-02-13 05:06 出处:网络
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 queu开发者_如何转开

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 queu开发者_如何转开发ed.

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?


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.)


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

0

精彩评论

暂无评论...
验证码 换一张
取 消