好的,我已经四处寻找,但找不到合适的答案。我有一个相当复杂的代码库,它使用Timer来启动后台工作程序的创建,以定期传输内容。
我在调用ReportProgress时遇到问题: “此操作已经调用了OperationCompleted,进一步调用是非法的。”
堆栈追踪:
at System.ComponentModel.AsyncOperation.VerifyNotCompleted()
at System.ComponentModel.AsyncOperation.Post(SendOrPostCallback d, Object arg)
at System.ComponentModel.BackgroundWorker.ReportProgress(Int32 percentProgress, Object userState)
at NAME.TX.Work(Object sender, DoWorkEventArgs e) in file.cs:line 68
at System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e)
at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument)
我的问题相对简单,当计时器关闭时调用的函数会创建一个新的后台工作者,但它实际上是一个新的后台工作者吗?
我的代码(简化因为它非常笨重):
//THIS IS THE FUNCTION CALLED BY TIMER
public void TransmitMSG(MSG msg)
{
//Initialze _tx
this.m_thread = new BackgroundWorker();
m_thread.WorkerReportsProgress = true;
//Initialize all events used by _tx
m_thread.DoWork += new DoWorkEventHandler(this.Work);
m_thread.ProgressChanged += new ProgressChangedEventHandler(this.Report);
m_thread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(this.Complete);
//Run the backgroundworker
m_thread.RunWorkerAsync(msg);
}
//THIS IS THE WORK FUNCTION
public override void Work(object sender, DoWorkEventArgs e)
{
//This code is in the TX Thread
//The sender should be the a BackgroundWorker
BackgroundWorker _tx = sender as BackgroundWorker;
//Check the Argument
if (e.Argument != null && e.Argument.GetType() == typeof(MSG))
{
//Transmit the Argument Message
m_THING.Transmit((MSG)e.MSG)
//Report progress according to the result
_tx.ReportProgress(CONSTANTS.PROGRESS.SUCCESS_TX, (MSG)e.Argument);
}
}
Work函数是一个覆盖,因为有一个更高的处理类允许传输和接收,这两个继承自同一个类,所以我可以有常见的ReportProgress和Close方法。