Results 1 to 2 of 2

Thread: [2.0] Cancelling Backgroundworker operation

  1. #1

    Thread Starter
    Fanatic Member Andy_P's Avatar
    Join Date
    May 2005
    Location
    Dunstable, England
    Posts
    669

    [2.0] Cancelling Backgroundworker operation

    In playing around with the BackgroundWorker, searching for examples on how to cancel it, I have come across this:
    c# Code:
    1. private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    2.         {
    3.            
    4.             for (int i = 0 ; i < 100 ; i++)
    5.             {
    6.                 lock (backgroundWorker1)
    7.                 {
    8.                     if (backgroundWorker1.CancellationPending)
    9.                     {
    10.                         e.Cancel = true;
    11.                         break;
    12.                     }
    13.                 }
    14.  
    15.                 System.Threading.Thread.Sleep(100);
    16.  
    17.                 backgroundWorker1.ReportProgress(0, i);
    18.             }
    19.         }
    The code is only doing some pointless loop, but my question is - Is the 'lock' operation necessary? Could reading the CancellationPending property at the same time CancelAsync() is called without locking the worker object cause a problem perhaps?

    I haven't seen this used anywhere else in the other examples I have found, so just looking for some opinions.

    Thanks.
    Using Windows XP Home sp3
    Mucking around with C# 2008 Express
    while ( this.deadHorse ) { flog( ); }


  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: [2.0] Cancelling Backgroundworker operation

    I can't think of any issue that might arise without the lock.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width