Notify when thread is complete, without locking calling thread

后端 未结 7 1315
既然无缘
既然无缘 2020-12-15 09:13

I am working on a legacy application that is built on top of NET 3.5. This is a constraint that I can\'t change. I need to execute a second thread to run a long running tas

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-15 09:30

    You can use a combination of custom event and the use of BeginInvoke:

    public event EventHandler MyLongRunningTaskEvent;
    
    private void StartMyLongRunningTask() {
        MyLongRunningTaskEvent += myLongRunningTaskIsDone;
        Thread _thread = new Thread(myLongRunningTask) { IsBackground = true };
        _thread.Start();
        label.Text = "Running...";
    }
    
    private void myLongRunningTaskIsDone(object sender, EventArgs arg)
    {
        label.Text = "Done!";
    }
    
    private void myLongRunningTask()
    {
        try 
        { 
            // Do my long task...
        } 
        finally
        {
            this.BeginInvoke(Foo, this, EventArgs.Empty);
        }
    }
    

    I checked, it's work under .NET 3.5

提交回复
热议问题