public void ReplayGame()
{
if (Class2.replayIsOn)
{
if (!backgroundWorker1.IsBusy)
{
backgroundWorker1.RunWorkerAsync();
}
}
}
我想在函数结束后立即取消/停止 backgroundwoker1.. backgroundworker 事件运行几秒钟然后停止..当它停止时我希望它结束!!..
我怎样才能完成那个任务/?没有得到我现在得到的任何无效操作异常
更新:
public void ReplayGame()
{
if (Class2.replayIsOn)
{
replay = serializeMeh.giveBackDictionary();
backgroundWorker1.WorkerSupportsCancellation = true;
backgroundWorker1.RunWorkerAsync();
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
int[] makeSelfMoves = new int[4];
if (!backgroundWorker1.CancellationPending)
{
lock (replay)
{
foreach (KeyValuePair<int, int[]> item in replay)// count should be more than 2
{
if (backgroundWorker1.CancellationPending)
{
break;
}
makeSelfMoves = replay[item.Key];
codeFile.ExecuteAll(makeSelfMoves[0], makeSelfMoves[1], makeSelfMoves[2], makeSelfMoves[3]);
PrintPieces(codeFile.PieceState()); Invalid operation exception is thrown here when chess pieces are drawn on the screen ... Two threads enter the loop simultaneously..:(...Invalid operation exception
System.Threading.Thread.Sleep(1000);
}
Class2.counter = serializeMeh.serializedCounter;
Class2.replayIsOn = false;
Game.WasntSerialized = true;
}
}
backgroundWorker1.CancelAsync();
}
最佳答案
您是否检查过工作人员是否支持取消?
backgroundWorker1.WorkerSupportsCancellation = true;
如果你没有显式设置它而你调用
backgroundWorker1.CancelAsync();
InvalidOperationException 将被抛出,因为默认情况下 worker 不支持异步取消。
更新
这只是检查工作人员状态的属性,如果您需要取消您需要调用的工作 backgroundWorker1.CancelAsync();
查看示例 here
关于c# - 中止线程(Backgroundworker)..需要建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6779243/