【发布时间】:2010-12-27 07:54:52
【问题描述】:
我正在编写一个在辅助线程上执行连续循环操作的 Visual C# 程序。有时,当该线程完成任务时,我希望它触发事件处理程序。我的程序会这样做,但是当事件处理程序被触发时,辅助线程会等到事件处理程序完成后再继续线程。我如何让它继续?这是我目前的结构方式...
class TestClass
{
private Thread SecondaryThread;
public event EventHandler OperationFinished;
public void StartMethod()
{
...
SecondaryThread.Start(); //start the secondary thread
}
private void SecondaryThreadMethod()
{
...
OperationFinished(null, new EventArgs());
... //This is where the program waits for whatever operations take
//place when OperationFinished is triggered.
}
}
此代码是我的一台设备的 API 的一部分。当 OperationFinished 事件被触发时,我希望客户端应用程序能够做它需要做的任何事情(即相应地更新 GUI)而不需要拖拽 API 操作。
另外,如果我不想将任何参数传递给事件处理程序,使用 OperationFinished(null, new EventArgs()) 的语法是否正确?
【问题讨论】:
-
您希望在哪个线程上引发
OperationFinished事件?它不能是您的辅助线程,因为您明确要求不要阻止它。那么,它是否必须是主线程,或者您是否可以在仅为异步回调目的而新创建的不同线程上引发它?
标签: c# multithreading event-handling synchronous eventargs