我有一个运行长时间操作的模型对象。我试图在线程中运行其中一些操作以保持界面响应,一次下载 2 个东西等,但我想尽可能地从界面代码中隐藏这些细节。我正在尝试使用 AsyncCall 库,但遇到了问题。
type EUpdaterAction = (auFoundCurrentVersion, auFoundUpdateVersion);
type
TUpdater = class
public
procedure loadCurrentVersion();
procedure notify(action: EUpdaterAction);
end;
procedure TUpdater.loadCurrentVersion();
begin
TAsyncCalls.Invoke(procedure
begin
Assert(Windows.GetCurrentThreadId() <> System.MainThreadID);
//Really long code
TAsyncCalls.VCLSync(procedure begin notify(auFoundCurrentVersion); end);
end);
end;
断言失败。我需要做些什么让它在单独的线程中运行,还是第一个 example shown with the library只是实际上没有在线程中运行?
最佳答案
您需要调用IAsyncCall.ForceDifferentThread
强制代码在不同的线程中运行。在您的示例中,TAsyncCalls.Invoke() 返回的接口(interface)立即释放,因为函数结束并释放 IAsyncCall 接口(interface)调用 Sync
方法。由于您的任务尚未开始,Sync
方法将在同一个线程中执行它,除非 ForceDifferentThread
方法被调用。
TAsyncCalls.Invoke(procedure
begin
Assert(Windows.GetCurrentThreadId() <> System.MainThreadID);
//Really long code
TAsyncCalls.VCLSync(procedure begin notify(auFoundCurrentVersion); end);
end).ForceDifferentThread; // <<<<<
但这真的是你想要的吗?我猜你想在 loadCurrentVersion() 退出后保持线程处于事件状态。对于这个 AsyncCalls 不是正确的工具。
关于delphi - 为什么 AsyncCall 在主线程中运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12333100/