c# - Aborting a thread (Backgroundworker).. need an advice -


        public void replaygame()     {          if (class2.replayison)         {              if (!backgroundworker1.isbusy)             {                 backgroundworker1.runworkerasync();             }         }                      } 

i wan cancel/stop backgroundwoker1 function ends.. backgroundworker event runs few seconds , stops..when stops want end!!..

how can achieve task/? without getting invalid operation exceptions 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 more 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 thrown here when chess pieces drawn on screen ... 2 threads enter loop simultaneously..:(...invalid operation exception                       system.threading.thread.sleep(1000);                 }                 class2.counter = serializemeh.serializedcounter;                 class2.replayison = false;                 game.wasntserialized = true;             }         }         backgroundworker1.cancelasync();     } 

did check worker support cancellation?

backgroundworker1.workersupportscancellation = true; 

if haven't explicitly set , call

backgroundworker1.cancelasync(); 

invalidoperationexception thrown, because default worker doesn't support asynch cancellation.

update
that's property checks workers's state, if need cancel work need call backgroundworker1.cancelasync();

see sample here


Comments

Popular posts from this blog

linux - Using a Cron Job to check if my mod_wsgi / apache server is running and restart -

actionscript 3 - TweenLite does not work with object -

jQuery Ajax Render Fragments OR Whole Page -