Is it possible to run an eventhandler in another thread

597 views Asked by At

I'm using an object that allows me to subscribe to events:

easyModbusTCPServer.holdingRegistersChanged += new EasyModbus.ModbusServer.HoldingRegistersChanged(RegistersChanged);

Whenever this event is triggered the function "RegistersChanged" is called and it starts or stops some "long running code" (stopping happens by changing a boolean "StopRunning" to "True")

Stopping the "long running code" unfortunately does not work. I think since the "long running code" is busy in the main thread, it blocks the eventhandler "registersChanged" from being reached....

Is it possible to have the function "RegistersChanged" called in a different thread, so the function "RegistersChanged" is still called and the "long running code" in the main thread can be stopped.


Instead of putting the eventhandler in a seperate thread, I could place the long running code in a seperate thread, but unfortunately this "long running code" is complex and requires communication with a lot of objects created in the main thread....

It is not important that the UI cannot be used while the code is running.

Thank you,

2

There are 2 answers

0
mm8 On

Is it possible to have the function "RegistersChanged" called in a different thread

Short answer: No, unless you can modify that code that actually raises the event. Then you can raise it on another thread. The event handler gets invoked on the same thread where the event is raised.

You can switch to another thread the first thing do inside the RegistersChanged event handler though.

unfortunately this "long running code" is complex and requires communication with a lot of objects created in the main thread....

Then you will have to rewrite it.

1
AudioBubble On

Not sure if this will help, but in my sample project Blazor Image Gallery, I login a user in another thread like this:

using System.Threading;
using System.Threading.Tasks;

// create a new loginModel object
LoginModel loginModel = new LoginModel(EmailAddress, Password, StoredPasswordHash, OnLoginComplete);

// Start the ProcessLogin Thread
Thread thread = new Thread(ProcessLogin);
thread.IsBackground = true;
thread.Start(loginModel);

Then my ProcessLogin method looks like this:

public static async void ProcessLogin(object data)
{
    // local
    LoginResponse loginResponse = null;

    // cast as a Loginmodel object
    LoginModel loginModel = data as LoginModel;

    // process login code removed

    // if the delegate exists
    if (NullHelper.Exists(loginModel.OnLoginComplete))
    {   
         // Call the delegate that the login has finished
         loginModel.OnLoginComplete(loginResponse);
    } 
}

If you want to see a full working version, here is a sample project and video:

Code: https://github.com/DataJuggler/BlazorImageGallery

Video: Building Blazor Image Gallery https://youtu.be/3xKXJQ4qThQ

Maybe it will give you some ideas, not sure if this will help you or not.