Search code examples
.netmultithreadingvb6

Calling VB6 COM Function from DotNet in multiple threads


I want to create an .net application which calls a VB6 COM function. The COM component is declared as Multiuse.

Private _App As ComObject = New ComObject

Public Sub Start()
    Dim Thread1 = New Threading.Thread(Sub() DoSomething())
    Dim Thread2 = New Threading.Thread(Sub() DoSomething())
    Dim Thread3 = New Threading.Thread(Sub() DoSomething())
    Thread1.Start()
    Thread2.Start()
    Thread3.Start()
End Sub

Private Sub DoSomething()
    _App.DoSomeComLogic
End Sub

The logic in the COM component takes about 10 seconds to proceed. But Thread3 is finished after 30 seconds.

Is there any way to multi-thread these function calls?
Do I need to add some DoEvents in the VB6 component?
Is there a better way to achieve this?


Solution

  • If you have the source to the VB6 component, I'd recommend just rewriting it in C# - you'll get a lot more out of it (64-bit execution, threading, better primitives, etc.) VB6 is very old, unmaintained technology with numerous restrictions. What you're trying to do is possible even with VB6 but is very, very complicated and hard to get right. (Much harder than doing the same in C#.)

    If the COM component is 3rd party and you cannot upgrade (meaning you have to use this old component), you can wrap your COM component (which I assume is a DLL) in an out-of-process COM server (an ActiveX EXE project in VB6).

    I don't have VB6 installed at the moment but if I remember right, you can set the new server to SingleUse so a new instance starts for every request. This would give you proper parallel processing using VB6, at the cost of handling every call in a separate process. (Each process would live for about 10 seconds - probably somewhat longer because of the extra process start-up cost.) Depending on how complex the old component is, this may be a lot of work.

    If you can, just convert your old VB6 component to C# - even if it's more work, at least you won't have to deal with it anymore and will be easier to maintain it going forward.