5

这是同步的问题。我对我的问题进行了简化,所以我有一个 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);

通常线程在进入关键部分时会给我错误,或者几秒钟后计时器将不再吸引我任何东西。

4

1 回答 1

10

尝试在您的代码中添加异常处理,并且不要同时锁定两个位图:

var
  csCriticalSection: TRTLCriticalSection;

procedure TMyForm.Add(iX,iY,iNr:integer);
begin
  EnterCriticalSection(csCriticalSection);
  try
    bmRed.Canvas.Lock;
    try
      bmRed.Canvas.TextOut(iX,iY,IntToStr(iNr));
    finally
      bmRed.Canvas.Unlock;
    end;

    bmBlue.Canvas.Lock;
    try
      bmBlue.Canvas.TextOut(iX,iY,IntToSTr(iNr));
    finally
      bmBlue.Canvas.Unlock;
    end;
  finally
     LeaveCriticalSection(csCriticalSection);
  end;
end;

procedure TMyForm.tmTimer(Sender: TObject);
begin
  EnterCriticalSection(csCriticalSection);
  try
    bmRed.Canvas.Lock;
    try
      imRed.Canvas.Draw(bmBlue);
    finally
      bmRed.Canvas.Unlock;
    end;

    bmBlue.Canvas.Lock;
    try
      imBlue.Canvas.Draw(bmBlue);
    finally
      bmBlue.Canvas.Unlock;
    end;
  finally
    LeaveCriticalSection(csCriticalSection);
  end;
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);

如果那仍然是崩溃/错误,那么您的代码中有一个未显示的不同错误。特别是考虑到您永远不应该在进入/离开临界区时出错,除非临界区本身已损坏。

于 2013-01-06T20:51:09.587 回答