0

I have the following code that uses new .NET 4.5 multi-threading functionality. Action2 is a call to a windows API library MLang through Interop.

    BlockingCollection<int> _blockingCollection= new BlockingCollection<int>(); 


    [Test]
    public void Do2TasksWithThreading()
    {
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();

        var tasks = new List<Task>();
        for (int i = 0 ; i < Environment.ProcessorCount; i++)
        {
            tasks.Add((Task.Factory.StartNew(() => DoAction2UsingBlockingCollection(i))));
        }

        for (int i = 1; i < 11; i++)
        {
            DoAction1(i);

            _blockingCollection.Add(i);
        }

        _blockingCollection.CompleteAdding();

        Task.WaitAll(tasks.ToArray());

        stopwatch.Stop();

        Console.WriteLine("Total time: " + stopwatch.ElapsedMilliseconds + "ms");
    }

    private void DoAction2UsingBlockingCollection(int taskIndex)
    {
        WriteToConsole("Started wait for Action2 Task: " + taskIndex);

        int index;
        while (_blockingCollection.Count > 0 || !_blockingCollection.IsAddingCompleted)
        {
            if (_blockingCollection.TryTake(out index, 10))
                DoAction2(index);
        }

        WriteToConsole("Ended wait for Action2 Task: " + taskIndex);
    }



    private void DoAction2()
    {
                    ... Load File bytes

        //Call to MLang through interop
        Encoding[] detected = EncodingTool.DetectInputCodepages(bytes[], 1);

                    ... Save results in concurrent dictionary
    }

I did some testing with this code and increasing number of threads from 1 to 2 to 3, etc.. doesn't make process run any faster. It looks like the the threads are waiting for interop call to finish, which makes me think that it is using single thread for some reason.

Here is the definition of Interop method:

namespace MultiLanguage
{
    using System;
    using System.Runtime.CompilerServices;
    using System.Runtime.InteropServices;
    using System.Security;

[ComImport, InterfaceType((short) 1), Guid("DCCFC164-2B38-11D2-B7EC-00C04F8F5D9A")]
public interface IMultiLanguage2

[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
    void DetectInputCodepage([In] MLDETECTCP flags, [In] uint dwPrefWinCodePage,
        [In] ref byte pSrcStr, [In, Out] ref int pcSrcSize, 
        [In, Out] ref DetectEncodingInfo lpEncoding, 
        [In, Out] ref int pnScores);

I there anything that can be done to make this use multiple threads? The only thing I noticed that would require single thread is MethodImplOptions.Synchronized, but that's not being used in this case.

The code for EncodingTools.cs was taken from here: http://www.codeproject.com/Articles/17201/Detect-Encoding-for-In-and-Outgoing-Text

5
  • what unit test runner are you using? Jul 8, 2013 at 7:44
  • I tried it in console app to check if NUnit maybe adding some overhead, but getting same results.
    – Eric P
    Jul 8, 2013 at 8:40
  • Your code should use multiple threads, you can see for yourself — just print managed thread id numbers or whatever. But you miss the real question: why should it run any faster with multiple threads? If it's I/O bound, adding threads won't help any. Jul 8, 2013 at 9:01
  • It does use multiple threads. I write out ThreadId in WriteToConsole method. It just seems like when all threads try to call interop call at the same time - it is locking and limiting to only single request at a time. I was just wondering if there some interop attribute or something else that I need to enable to prevent locking. MLang uses heuristics to detect CodePage or Text Encoding, so it seems that it would be CPU bound task.
    – Eric P
    Jul 8, 2013 at 9:05
  • More info on MLang is here: msdn.microsoft.com/en-us/library/aa767865(v=vs.85).aspx. Wonder if it is not CPU bound, but hard to see how it could be.
    – Eric P
    Jul 8, 2013 at 9:08

2 Answers 2

3
  ... Load File bytes

Threads can speed up your program when your machine has multiple processor cores, easy to get these days. Your program is however liable to spend a good bit of time on this invisible code, disk I/O is very slow compared to the raw processing speed of a modern processor. And you still have only a single disk, there is no concurrency at all. Threads will just wait their turn to read data from the disk.

[ComImport, InterfaceType((short) 1), Guid("DCCFC164-2B38-11D2-B7EC-00C04F8F5D9A")]
public interface IMultiLanguage2

This is a COM interface, implemented by the CMultiLanguage coclass. You can find it back in the registry with Regedit.exe, the HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID\{275C23E2-3747-11D0-9FEA-00AA003F8646} key contains the configuration for this coclass. Threading is not a detail left up to the client programmer in COM, a COM coclass declares what kind to threading it supports with the ThreadingModel key.

The value for CMultiLanguage is "Both". Which is good news, but it now greatly matters exactly how you created the object. If the object is created on an STA thread, the default for the main thread in a Winforms or WPF project, then COM ensures all the code stays thread-safe by marshaling interface method calls from your worker thread to the STA thread. That will cause loss of concurrency, the threads take their turn entering the single-threaded apartment.

You can only get concurrency when the object was created on an MTA thread. The kind you get from a threadpool thread or your own Thread without a call to its SetApartmentState() method. An obvious approach to ensure this is to create the CMultiLanguage object on the worker thread itself and avoid having these worker threads shared the same object.

Before you start fixing that, you first need to identify the bottleneck in the program. Focus on the file loading first and make sure you get a realistic measurement, avoid running your test program on the same set of files over and over again. That gives unrealistically good results since the file data will be read from the file system cache. Only the first test after a reboot or file system cache reset gives you a reliable measurement. The SysInternals' RamMap utility is very useful for this, use its Empty + Empty Standby List menu command before you start a test to be able to compare apples to apples.

If that shows that the file loading is the bottleneck then you are done, only improved hardware can solve that. If however you measure that IMultiLanguage2 calls then focus on the usage of the CMultiLanguage object. Without otherwise a guarantee that you can get ahead, a COM server typically provides thread-safety by taking care of the locking for you. Such hidden locking can ruin your odds for getting concurrency. The only way to get ahead then is to get the file reading in one thread to overlap with the parsing in another.

6
  • Thank you Hans. I load files outside of the threaded code and just pass loaded content, so there shouldn't be any IO usage. IMultiLanguage2 calls take 95%+ of the processing time. I will look into STA threads.
    – Eric P
    Jul 8, 2013 at 12:06
  • One more thing. I looked for "275C23E1-3747-11D0-9FEA-00AA003F8646" in registry through RegEdit -> Find, but it returned no results. Not sure why it is not in Registry.
    – Eric P
    Jul 8, 2013 at 12:27
  • It's there, your program would bomb if it were not. Navigate directly to the path I documented. This otherwise is just a detail, you cannot change anything there. Don't make the mistake of messing with a ThreadingModel key, it won't come to a good end. Jul 8, 2013 at 12:32
  • Found it by going directly to path. It says ThreadingModel: both. I guess it should allow for multi-threading.
    – Eric P
    Jul 8, 2013 at 12:37
  • Shoot I missed that. I had to substantially revise the answer. Jul 8, 2013 at 12:55
0

Try running nunit-console with parameter /apartment=MTA

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.