Why doesn't multithreading in C# reach 100% CPU?

前端 未结 13 1323
眼角桃花
眼角桃花 2021-01-30 22:17

I\'m working on a program that processes many requests, none of them reaching more than 50% of CPU (currently I\'m working on a dual core). So I created a threa

相关标签:
13条回答
  • 2021-01-30 22:30

    if your process is running on cpu 0 and spawning threads there, the maximum it will ever reach is 50%. See if you have threads running on both cores or on just one. I would venture to guess you're isolated to a single core, or that one of your dependent resources is locked on a single core. If it hits exactly 50% then a single core is very likely to be your bottleneck.

    0 讨论(0)
  • 2021-01-30 22:32

    It depends what your program does - the work carried out by your concurrent Requests could be IO-bound - limited by the speed of (eg) your hard disk - rather than CPU bound, when you would see your CPU hit 100%.

    After the edit, it does sound like COM STA objects might be the culprit.

    Do all threads call the same instance of the COM object? Would it be possible to make your worker thread STA threads, and create a separate instance of the COM object on each thread. In this way it might be possible to avoid the STA bottleneck.

    To tell if a COM coclass is STA:

    class Test
    {
      static void Main() //This will be an MTA thread by default
      {
        var o = new COMObjectClass();
        // Did a new thread pop into existence when that line was executed?
        // If so, .NET created an STA thread for it to live in.
      }
    }
    
    0 讨论(0)
  • 2021-01-30 22:33

    The problem is the COM object. It is STA, and I can't either have two instances running concurrently on the same process. When I create an instance for the COM class, the other becomes unusable.

    I've contacted the component developers, they're thinking what they can do for me.

    Thanks you all ;)

    0 讨论(0)
  • 2021-01-30 22:34

    It sounds like your application's performance may not be 'bound' by the amount of cpu resources available. If you're processing requests over the network, the cpu(s) may be waiting for the data to arrive, or for the network device to transfer the data. Alternatively, if you need to look up data to fulfill the request, the cpu may be waiting for the disk.

    0 讨论(0)
  • 2021-01-30 22:40

    It is probably no longer the processor that is the bottleneck for completing your process. The bottleneck has likely moved to disk access, network access or memory access. You could also have a situation where your threads are competing for locks.

    Only you know exactly what your threads are doing, so you need to look at them with the above in mind.

    0 讨论(0)
  • 2021-01-30 22:40

    One more note, have you tried launching your code not from Visual Studio (regardless of release / debug settings) ?

    0 讨论(0)
提交回复
热议问题