Run code on a specific thread

Martin 21 Reputation points
2022-06-14T10:22:56.113+00:00

I'm building a class library that requires me to run specific code on the same thread that created the class instance. This becomes a problem when code is started in new threads or backgroundworkers. Let's take the following code for example:

Imports System.Runtime.InteropServices  
Imports System.Threading  
  
<ComVisible(True),  
    ClassInterface(ClassInterfaceType.AutoDual)>  
Public Class ThreadTest  
  
    Private StartingThread As Thread  
  
    Public Sub New()  
        StartingThread = Thread.CurrentThread  
        Console.WriteLine("Starting thread Id: " & StartingThread.ManagedThreadId)  
    End Sub  
  
    Public Sub DoStuffThreaded()  
        Dim t As New Thread(  
            Sub()  
                RunOnStartingThread()  
            End Sub)  
        t.Start()  
    End Sub  
  
    Public Sub RunOnStartingThread()  
        Console.WriteLine("Starting thread Id: " & StartingThread.ManagedThreadId)  
        Console.WriteLine("Current thread Id: " & Thread.CurrentThread.ManagedThreadId)  
  
        MsgBox("Starting thread Id: " & StartingThread.ManagedThreadId & vbNewLine &  
                "Current thread Id: " & Thread.CurrentThread.ManagedThreadId, vbInformation, "Test")  
    End Sub  
  
End Class  

When I call the method RunOnStartingThread the output will show that it has the same thread Id on the starting thread and the current thread. But when I call method DoStuffThreaded it will give different Id's for the starting thread and current thread.

I know that when using forms I can use BeginInvoke to run code on the main thread but in this case I don't have a form. Is there a way to "invoke" code without an UI to be run on the main thread? Or in this case on the starting thread because that is where the code needs to run.

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
1,845 questions
{count} votes