delphi - 为什么 AsyncCall 在主线程中运行?

标签 delphi asynchronous delphi-2010

我有一个运行长时间操作的模型对象。我试图在线程中运行其中一些操作以保持界面响应,一次下载 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/

相关文章:

delphi - 如何确定 TEdit 的输入区域大小?

delphi - Delphi 2010 有新的 ORM 吗?

delphi - 如何在Delphi中显示半透明的暗淡面板/图像?

delphi - 来自字符串的枚举

delphi - 修改TActionToolBar中分割按钮的 "arrow"

delphi - 在 Delphi 中写入 EXE

c++ - CryptoAPI 和 XMLDSIG c、c++、delphi

javascript - 如果 Promise 尚未结算,那么 then 之后的代码如何运行?

swift - 在序列 Swift 中运行两个 Alamofire 请求

java - 当同一部分被调用两次时,CompletableFuture 的 "SupplyAsync"部分会发生什么