0

I have two thread ,Each running two threads, no error appear. but run together,the backgroundWorker2 tip :can't clone null.....(I check variable J value is greater than 100),in this case,how to lock global variable?

Bitmap img; //global variable
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        int i = 0;
        do
        {
            img = (Bitmap)Image.FromFile(@"i:\1.jpg");
            img.Dispose();
            i++;
            backgroundWorker3.ReportProgress(i,"");
            Thread.Sleep(10);
        } while (!backgroundWorker4.CancellationPending);
    }

 private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
    {
        int j= 0;
        do
        {
            //img = (Bitmap)Image.FromFile(@"i:\1.jpg");

            if (img != null)
            {
                lock (img)
                {
                    Bitmap tempImg = (Bitmap)img.Clone();
                }
            }

            j++;
            backgroundWorker4.ReportProgress(j, "");
            Thread.Sleep(10);
        } while (!backgroundWorker4.CancellationPending);
    }
ksugiarto
  • 940
  • 1
  • 17
  • 40
zenith
  • 51
  • 1
  • 7

1 Answers1

1

It looks like you need a double-checked lock. This prevents the scenario where, in between the null check and the locking, another thread sets img to null (ie, a race condition).

if (img != null)
{
    lock (img)
    {
        if (img != null)
        {
            Bitmap tempImg = (Bitmap)img.Clone();
        }
    }
}
Community
  • 1
  • 1
McGarnagle
  • 101,349
  • 31
  • 229
  • 260
  • Will it really work to lock `img` itself, since the value of that variable is being repeatedly changed, or is it actually necessary to (double-)lock *access* to img using some other object like a `readonly object _lock = new object()` or (fast-and-loose) `this`? And is the lock also required when *setting* img, as well as when reading it? – Eric Sep 13 '13 at 01:59
  • @Eric yes you're right, I'm sorry. You have to use another object for the to lock -- otherwise the lock gets released when a new object is assigned to `img`. – McGarnagle Sep 13 '13 at 20:15
  • @Eric and yes, you also want to lock when setting img -- acquiring the lock is what guarantees that the current section will be the only one accessing the variable. – McGarnagle Sep 13 '13 at 20:17