且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何等待一个线程在C#中完成执行?

更新时间:2021-10-21 09:08:04

这是它是如何做。创建类,没有工作:

This is how it's done. Create class that does the job:

public class MyAsyncClass
{

    public delegate void NotifyComplete(string message);
    public event NotifyComplete NotifyCompleteEvent;

    //Starts async thread...
    public void Start()
    {
        System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(DoSomeJob));
        t.Start();
    }

    void DoSomeJob()
    {
        //just wait 5 sec for nothing special...
        System.Threading.Thread.Sleep(5000);
        if (NotifyCompleteEvent != null)
        {
            NotifyCompleteEvent("My job is completed!");
        }
    }
}

现在这个代码从另一个类,调用第一个:

Now this is code from another class, that calls first one:

 MyAsyncClass myClass = null;


    private void button2_Click(object sender, EventArgs e)
    {
        myClass = new MyAsyncClass();
        myClass.NotifyCompleteEvent += new MyAsyncClass.NotifyComplete(myClass_NotifyCompleteEvent);
        //here I start the job inside working class...
        myClass.Start();
    }

    //here my class is notified from working class when job is completed...
    delegate void myClassDelegate(string message);
    void myClass_NotifyCompleteEvent(string message)
    {
        if (this.InvokeRequired)
        {
            Delegate d = new myClassDelegate(myClass_NotifyCompleteEvent);
            this.Invoke(d, new object[] { message });
        }
        else
        {
            MessageBox.Show(message);
        }
    }

让我知道如果我要解释一些细节。

Let me know if I need to explain some details.

替代,这是的 BackgroudWorker