这是同步的问题。我对我的问题进行了简化,所以我有一个 VCL Timer 和几个线程。线程试图在两个位图中写入内容,计时器试图将位图绘制到图像(TImage)中。这是我的代码的修改,更容易理解(这个粘贴代码很模糊)。
//------------------------------------------------------------------------------
Procedure TMyForm.Add(iX,iY,iNr:integer);
begin
EnterCriticalSection(csCriticalSection);
bmRed.Canvas.Lock;
bmBlue.Canvas.Lock;
//.... drawing etc...
bmRed.Canvas.TextOut(iX,iY,IntToStr(iNr));
bmBlue.Canvas.TextOut(iX,iY,IntToSTr(iNr));
bmRed.Canvas.Unlock;
bmBlue.Canvas.Unlock;
LeaveCriticalSection(csCriticalSection);
end;
//------------------------------------------------------------------------------
procedure TMyForm.tmTimer(...);
begin
EnterCriticalSection(csCriticalSection);
bmRed.Canvas.Lock;
bmBlue.Canvas.Lock;
//Drawing on bmRed and bmBlue
imBlue.Canvas.Draw(bmBlue);
imRed.Canvas.Draw(bmBlue);
bmRed.Canvas.Unlock;
bmBlue.Canvas.Unlock;
LeaveCriticalSection(csCriticalSection);
end;
//------------------------------------------------------------------------------
Procedure TMyThread.Execute();
begin
Randomize;
while not terminated do
begin
MyFormInstance.Add(Random(100),Random(100),Random(100));
Sleep(20);
end;
end;
initialization
InitializeCriticalSection(csCriticalSection);
finalization
DeleteCriticalSection(csCriticalSection);
通常线程在进入关键部分时会给我错误,或者几秒钟后计时器将不再吸引我任何东西。