Ond*_* C. 13 c# delphi multithreading delphi-6
我正在Delphi中编写一个多线程应用程序,需要使用一些东西来保护共享资源.
在C#中,我使用"lock"关键字:
private someMethod() {
lock(mySharedObj) {
//...do something with mySharedObj
}
}
Run Code Online (Sandbox Code Playgroud)
在Delphi中我找不到类似的东西,我发现只有TThread.Synchronize(someMethod)方法,它通过在主VCL线程中调用someMethod来防止潜在的冲突,但它并不是我想要做的......
编辑:我正在使用Delphi 6
ang*_*son 17
(联合国)幸运的是你无法锁定Delphi 6中的任意对象(尽管你可以在更新版本,2009及更高版本中使用),因此你需要一个单独的锁对象,通常是一个关键部分.
TCriticalSection(注意:文档来自FreePascal,但它也存在于Delphi中):
示例代码:
type
TSomeClass = class
private
FLock : TCriticalSection;
public
constructor Create();
destructor Destroy; override;
procedure SomeMethod;
end;
constructor TSomeClass.Create;
begin
FLock := TCriticalSection.Create;
end;
destructor TSomeClass.Destroy;
begin
FreeAndNil(FLock);
end;
procedure TSomeClass.SomeMethod;
begin
FLock.Acquire;
try
//...do something with mySharedObj
finally
FLock.Release;
end;
end;
Run Code Online (Sandbox Code Playgroud)
Rob*_*edy 11
在Delphi 6中没有等价物.从Delphi 2009开始,您可以使用这些System.TMonitor方法来获取任意对象的锁定.
System.TMonitor.Enter(obj);
try
// ...
finally
System.TMonitor.Exit(obj);
end;
Run Code Online (Sandbox Code Playgroud)
(您需要"System"前缀,因为TMonitor名称与Forms单元中的类型冲突.另一种方法是使用global MonitorEnter和MonitorExitfunctions.)