如果我使用invoke从另一个线程更新表单,如何正确关闭winform

时间:2015-03-26 10:44:50

标签: c# multithreading winforms

我有一个winform,用于订阅来自回调接口的事件。我用......

public partial class Form1 : Form  
{ 
    MyTestCallBack _callback;

    public Form1() 
    {

        InitializeComponent();
        //Start otherthread
        API.Create()

        _callback = new MyTestCallBack();
        _callback.MyTestCallBackEvent += callback_MyTestCallBackEvent;
        _callback.OnUpdate(); 
    }

    private callback_MyTestCallBackEvent(MyTestCallBackEventArgs e) 
    {
        if (InvokeRequired)
        {
            Invoke(new Action(() =>
            {
                callback_MyTestCallBackEvent(sender, e);
            }));
            return;
        }
        label1.Text = e.SomeObject.GetDisplayString(); 
    } }

    class MyTestCallBackEventArgs : EventArgs   {
        public SomeObject SomeObj { get; set; }   }

    class MyTestCallBack : Callback   {
        public event EventHandler<MyTestCallBackEventArgs> MyTestCallBackEvent;


    protected virtual void OnMyTestCallBackEvent(MyTestCallBackEventArgs e) 
    {
        if (MyTestCallBackEvent != null)
            MyTestCallBackEvent(this, e); 
    }

    public void OnUpdate(SomeObject someobj) 
    {
        OnMyTestCallBackEvent(new MyTestCallBackEventArgs { SomeObject = someobj }); 
    }  
}
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        //tried this but still crashes
        _callback.MyTestCallBackEvent -= callback_MyTestCallBackEvent;
        API.Destroy()
    }

当我尝试关闭我的表单时,它会崩溃。 “冻结”。我认为这是因为另一个线程没有正确地缩小。

如何安全取消订阅此活动,以便我可以正确关闭。

1 个答案:

答案 0 :(得分:1)

要立即取消订阅活动,请使用:

_callback.MyTestCallBackEvent -= callback_MyTestCallBackEvent;