public void ReplayGame()
{
if (Class2.replayIsOn)
{
if (!backgroundWorker1.IsBusy)
{
backgroundWorker1.RunWorkerAsync();
}
}
}
I wan to cancel/stop backgroundwoker1 as soon as the function ends.. the backgroundworker event runs for a few seconds and stops..when it stops I want it to end!!..
How can I achieve that task/? without getting any invalid operation exceptions that i am getting now
UPDATE:
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();
}
Did you check that the worker support cancellation?
If you haven’t explicitly set it and you call
InvalidOperationException will be thrown, because by default worker doesn’t support asynch cancellation.
UPDATE
That’s just the property that checks the workers’s state, if you need to cancel the work you need to call
backgroundWorker1.CancelAsync();See a sample here