如何在多线程中锁定全局变量?

时间:2013-09-13 01:37:57

标签: c#

我有两个线程,每个线程运行两个线程,没有出现错误。但是一起运行,backgroundWorker2提示:无法克隆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);
    }

1 个答案:

答案 0 :(得分:1)

看起来你需要double-checked lock。这可以防止在null检查和锁定之间,另一个线程将img设置为null(即race condition)的情况。

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