我有两个线程,每个运行两个线程,没有出现错误。但是一起运行,后台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);
}