繁体   English   中英

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

[英]How to wait for a thread to finish execution in C#?

我有一个快速连续调用的函数,它具有打开的数据库连接。 我的问题是,在关闭一个数据库连接之前,将调用该函数的另一个实例,并且我可能会在数据库中收到死锁。

我努力了:

private static WaitHandle[] waitHandles = new WaitHandle[]
    {
        new AutoResetEvent(false)
    };

protected override void Broadcast(Data data, string updatedBy)
    {
        Action newAction = new Action(() =>
        {
        DataManagerFactory.PerformWithDataManager( 
            dataManager =>
            {
                // Update status and broadcast the changes
                data.UpdateModifiedColumns(dataManager, updatedBy);

                BroadcastManager.Instance().PerformBroadcast(
                    data,
                    BroadcastAction.Update,
                    Feature.None);
            },
            e => m_log.Error(ServerLog.ConfigIdlingRequestHandler_UpdateFailed() + e.Message));
            }
        );

        Thread workerThread = new Thread(new ThreadStart(newAction));
        ThreadPool.QueueUserWorkItem(workerThread.Start, waitHandles[0]);
        WaitHandle.WaitAll(waitHandles);
    }

但我收到线程错误,程序冻结。 我认为它与没有参数的线程启动功能有关。

谢谢你的帮助

这是完成的方式。 创建完成任务的类:

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!");
        }
    }
}

现在,这是另一个类的代码,它调用第一个类:

 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);
        }
    }

让我知道是否需要解释一些细节。

替代方法是BackgroudWorker

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM