Multithreading Delphi:如何使VCL在与来自另一个线程的数据交互时控制线程安全?
在一个单元Multithreading Delphi:如何使VCL在与来自另一个线程的数据交互时控制线程安全?,multithreading,delphi,synchronization,vcl,Multithreading,Delphi,Synchronization,Vcl,在一个单元DeviceManager中,我有一个VCL表单formDeviceManager,它与另一个TThread,DetectDriveThread中的数据交互检测驱动线程以程序的主要形式创建和执行 procedure TDetectDrivesThread.Execute; begin while not Terminated do begin sleep(1000); try DetectDrives.refreshRemovableDrivesLi
DeviceManager
中,我有一个VCL表单formDeviceManager
,它与另一个TThread
,DetectDriveThread
中的数据交互<代码>检测驱动线程以程序的主要形式创建和执行
procedure TDetectDrivesThread.Execute;
begin
while not Terminated do
begin
sleep(1000);
try
DetectDrives.refreshRemovableDrivesList(formMain.dbConn);
finally
end;
end;
end;
这是TDetectDrivesThread的构造函数:
constructor TDetectDrivesThread.Create();
begin
inherited Create(false);
DetectDrives := TDetectDrives.Create(formMain.dbConn);
FreeOnTerminate := false;
end;
formDeviceManager
具有多个控件,允许用户查看、删除和更改有关此类驱动器的数据。但是,我的控件不是线程安全的,当执行DetectDriveThread
时,我可以使用formDeviceManager
中的“删除设备”按钮来释放与USB设备对应的对象。如果该对象中的任何方法正在运行,这可能会导致程序崩溃。如果这是一个基本问题,很抱歉,我对多线程不太了解,这是我第一个正确的编码项目。你的方法注定会失败。我建议您阅读本文以更好地理解线程。无论如何,使用线程检测(USB?)驱动器不是正确的方法,如果使VCL控件线程安全那么简单,您可以得到,我想Embarcadero早就自己做到了。您应该将用户界面(UI、表单)和处理解耦(可能是您的DeviceManager)。将UI放在一个单元中,将处理放在另一个单元中。您的DeviceManager应该是一个类,它封装了一个TThread,以在工作线程中执行冗长的进程。然后,您可以使用标准的保护数据(使用关键部分和类似对象)使该类线程安全。