Feedback

C# - Events aus Worker-Thread im GUI-Thread werfen! Kein Invoke!

Veröffentlicht von am 3/11/2009
(1 Bewertungen)
Zeigt die Verwendung von AsyncOperation um Events aus einem Worker-Thread im GUI-Thread zu werfen. Somit fällt für jeglichen Code in den Event-Handlern in Bezug auf Control.Invoke() weg.
public partial class Form1 : Form
{
    public event EventHandler Tested;

    public Form1()
    {
        InitializeComponent();

        Tested += new EventHandler(Form1_Tested);
    }

    private void Form1_Tested(object sender, EventArgs e)
    {
        Text = "Test";
    }

    private void Form1_Shown(object sender, EventArgs e)
    {
        #region Test 1
        // Works normal in GUI-Thread directly
        Form1_Tested(this, EventArgs.Empty);
        #endregion

        #region Test 2
        // Works in worker thread and throws GUI exception 
        // because of foreign thread access
        new Thread(new ThreadStart(delegate()
            {
                OnTested(EventArgs.Empty);
            })).Start();
        #endregion

        #region Test 3
        // Works in worker thread and returns to GUI-Thread
        // to throw the event, so no need in eventhandler 
        // to use Control.Invoke();
        AsyncOperation asyncOp = AsyncOperationManager.CreateOperation(null);
        new Thread(new ThreadStart(delegate()
            {
                asyncOp.Post(new SendOrPostCallback(delegate(object obj)
                    {
                        OnTested(EventArgs.Empty);
                    }), null);
            })).Start();
        #endregion
    }

    protected virtual void OnTested(EventArgs e)
    {
        EventHandler tmpHandler = Tested;
        if (tmpHandler != null)
            tmpHandler(this, e);
    }
}

Kommentare zum Snippet

 

Logge dich ein, um hier zu kommentieren!