开发者

.NET: Overhead of Threading

Suppose I have two threads: A and B. When A creates an object(for example a List of String), and passes it to B for processing. Will there a performance decrease for each time B access this object? Or will th开发者_C百科ere be a one-time penalty while the object is marshalled from A to B?


There is no marshalling between threads in .NET. Both threads will interact with the same memory for storage associated with the object. There is no performance overhead for having one thread rather than another perform an operation on the object.

You need to worry about synchronisation between threads to ensure thread safety, not performance.


The threads live in the same memory space, so there is no marshalling, and no penalty for accessing objects.

However, as they share the memory you have to synchronise the access to the objects so that anything that is ever changed is only accessed by one thread at a time. When one thread is accessing an object the other thread has to wait, so that will cause a bit of overhead.


Just because you are using multiple threads in .Net does not imply marshaling will be used. Marshaling comes into play when you are sharing objects across AppDomains.

Assuming there are no AppDomains then the overhead you would pay would be locking - making sure only one thread accesses the object at a time. Each time you lock and unlock an object it will take up some CPU cycles.

Using multiple threads can also add other penalties - for example if you have to swap from thread A to thread B to complete some task then there may be the penalty of a thread switch. If the CPU has to put thread A to bed and wake up thread B then there will be some processor cycles spent doing this. Even if thread A and thread B are running on different CPUs but modifying common data then data in the CPU caches may have to be discarded (cache sloshing). Just a warning that you might try to speed something up by processing in parallel but end up slowing your app down.

Marshaling would be used if you are accessing an object created in one .Net AppDomain from another. And, depending on the type of marshaling you are using you could either go for the one time penalty (marshal by value) or the per call penalty (marshal by reference).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜