简体   繁体   中英

c# calling back to main thread

I'm in a static class in a background thread , but i want to create a new GUI component, to do this i need the main thread of the application to executing the method.

How can I do this?

[note i dont think i can use InvokeRequired as its a static class not a gui]

David

To clarify this issue, you have a Static class on a secondary thread that you would like to have your main thread spawn a UI element from this class.

In order to do this you will need to setup an event in your static class, and then have your UI listen for that event. Even if its static this can be wired up. In your event handle code you can have your main UI call invoke to actually spawn the UI element.

class Program
{
    static void Main(string[] args)
    {
        DoSomething.OnNeedsUI += new EventHandler<EventArgs>(DoSomething_OnNeedsUI);
        Thread t = new Thread(new ThreadStart(DoSomething.Work));
        t.Start();
    }

    private static void DoSomething_OnNeedsUI(object sender, EventArgs e)
    {
        Console.Write("Call Back Handled Here");
    }
}


public static class DoSomething
{
    public static void Work()
    {
        for (int i = 0; i < 10; i++)
        {

            Thread.Sleep(5000);
            // Raise your Event so the tUI can respond
            RaiseOnNeedsUI();
        }
    }

    //  Create a Customer Event that your UI will Register with
    public static event EventHandler<EventArgs> OnNeedsUI;
    private static void RaiseOnNeedsUI()
    {
        if (OnNeedsUI != null)
            OnNeedsUI(null, EventArgs.Empty);
    }

Your static class needs a reference to some instance class that was created on the UI thread, preferably a control. Since you're creating a control, you probably have some form/window in mind for that control, so you'll need a reference anyway. You can use the form's Invoke() method to marshall a call that will create the control on the UI thread.

You can either pass an instance of a UI control to the method (then fall Invoke on that), else wrap up what you want as a delegate; for example:

static void DoStuff(..., Action<string> updateMessage) {
    ...
    //loop
    updateMessage(currentState);
}

With:

DoStuff(..., msg => this.Invoke((MethodInvoker)delegate{
    this.Text = msg;
}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM