gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 16:23:34 24 4
gpt4 key购买 nike

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

我试过:

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 :

关于c# - 如何等待线程在 C# 中完成执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13241888/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com