I have my own COM library that returns an array of integers (in its own native format, of course). When I access this array from the main UI thread, everything is fine and works fast. When I access it from another thread, access is very slow. Here is the sample code below.
private void test() { ProprietaryLib.Integers ints = ProprietaryLib.GetInts(); int x; for(int i = 0; i < 500; i++) for(int j = 0; j < ints.Count; j++) x = ints[j]; } private void button1_Click(object sender, EventArgs e) { test();
Why is this happening? Is there any way to speed this up? If I use multiprocessing instead of multithreading, then will I have any hope of getting good performance? (Wow, though, sounds a lot more complicated.)
UPDATE:
I am satisfied with the answers below, but wanted to add some data here for reference (my own and others).
Creating and accessing an object in a new thread, as shown above, gives about 12 ns access. Presumably, the object is actually created in the main thread, and slow speed is associated with data marshaling from there.
If you explicitly create data in the main stream, but get access to it in a new stream marked as a single-threaded apartment, the access time is even slower - 15 ns per access. I believe that .NET should have extra overhead to keep the apartment in good condition, although it bothers me that I do not know what this overhead is. With a difference of 2-3 ns this should not be much.
If you create and access an object in a new thread marked by STA, the time will melt in .2ns per access. But is this new thread really safe? This is a question for another question that I think.
source share