C#C
C#13mo ago
stigzler

Calling a method in a class running on a separate thread from the main thread

Hi. I'm not very good at threading stuff!

I'm developing a plugin for a 3rd party app. The app provides hooks via a ISystemEventsPlugin interface. Whenever an event happens in the app, it is raised in this interface.

I am wanting to start a class ("process"?) on another thread with its being instantiated by a specific event fired by the app (SystemEventTypes.BigBoxStartupCompleted). This is only fired once. I have successfully instantiated the desired class on another thread (I think - it runs OK and I can see it as a separate thread in the "Parallel Stacks" debug window). However, my query is how do I pass subsequent SystemEventTypes firings to this instance.

The way I do it at the moment appears to work functionally, but it doesn't feel right as I'm essentially doing a cross-thread call. Here's my code presently:

internal class SystemEventsHook : ISystemEventsPlugin
{
    private BigBoxViewController BigBoxViewController;

    [STAThread]
    public void OnEventRaised(string eventType)
    {
        switch (eventType)
        {
            case SystemEventTypes.PluginInitialized:
                Initialization.InitialiseGearbox();
                break;

            case SystemEventTypes.BigBoxStartupCompleted:

                Thread bigBoxThread = new Thread(new ThreadStart(() =>
                {
                    BigBoxViewController = new BigBoxViewController(this);
                    BigBoxViewController.OnBigBoxStartupCompleted();
                    System.Windows.Threading.Dispatcher.Run();
                    
                }));
                bigBoxThread.SetApartmentState(ApartmentState.STA);
                bigBoxThread.IsBackground = true;
                bigBoxThread.Name = "BigBoxViewController";
                bigBoxThread.Start();
                break;
        }

        if (BigBoxViewController != null)
        {
            BigBoxViewController.ProcessSystemEvent(eventType);
        }
    }
}
Was this page helpful?