メインスレッドで登録されたイベントを別スレッドから呼び出すときのメモ。

以下コード。

static class EventInvoker
{
    static public void Invoke<TEventHandler>(TEventHandler handler, object[] args)
    {
        System.Delegate d = handler as System.Delegate;
        System.ComponentModel.ISynchronizeInvoke invoker = d.Target as System.ComponentModel.ISynchronizeInvoke;
        invoker.Invoke(d, args);
    }

    static public System.IAsyncResult BeginInvoke<TEventHandler>(TEventHandler handler, object[] args)
    {
        System.Delegate d = handler as System.Delegate;
        System.ComponentModel.ISynchronizeInvoke invoker = d.Target as System.ComponentModel.ISynchronizeInvoke;
        return invoker.BeginInvoke(d, args);
    }
}

class TestClass
{
    private System.Threading.Thread thread = new System.Threading.Thread(
        new System.Threading.ParameterizedThreadStart(ThreadCallback));

    public delegate void TestEventHandler(object sender, System.EventArgs e);

    public event TestEventHandler OnTest;

    public void Start()
    {
        this.thread.Start(this);
    }

    private void ThreadCallback(object obj)
    {
        TestClass tc = obj as TestClass;
        tc.CallEventHandler();
    }

    private void CallEventHandler()
    {
        if(this.OnTest != null)
        {
            EventInvoker.Invoke(OnTest, new object[] { "test", new System.EventArgs() });
        }
    }
}

/// ----- Main Form Source -----

private tc_OnTest(object sender, EventArgs e)
{
    MessageBox.Show((string)sender);
}

TestClass tc = new TestClass();
tc.OnTest += new TestClass.TestEventHandler(tc_OnTest);
tc.Start();

/// ----- EOF -----

関連性がある記事

Disqusでコメント