0

我有两个线程,每个运行两个线程,没有出现错误。但是一起运行,后台Worker2提示:can't clone null.....(我检查变量J值是否大于100),这种情况下,如何锁定全局变量?

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);
    }
4

1 回答 1

1

看起来你需要一个双重检查锁。这可以防止在空检查和锁定之间,另一个线程设置img为空(即竞争条件)的情况。

if (img != null)
{
    lock (img)
    {
        if (img != null)
        {
            Bitmap tempImg = (Bitmap)img.Clone();
        }
    }
}
于 2013-09-13T01:41:27.520 回答