简体   繁体   English

尝试..除了在线程内被忽略

[英]Try..Except ignored inside a thread

I have a basic try..except to catch errors when trying to load a PNG file into a TImage :在尝试将 PNG 文件加载到TImage时,我有一个基本的try..except来捕获错误:

try
  Previewimage.Picture.LoadFromFile(filename);
except
  //code to handle exception
end;

Normally this works fine if the file does not exist, or in my case the PNG is corrupted.通常,如果文件不存在,或者在我的情况下 PNG 已损坏,这可以正常工作。 I have no control over the source creation of the PNG, so need to catch when the PNG cannot be loaded, ie it gives the error:我无法控制PNG的源代码创建,因此需要在无法加载PNG时捕获,即它给出了错误:

This "Portable Network Graphics" image is not valid because it contains invalid pieces of data (crc error).此“便携式网络图形”图像无效,因为它包含无效的数据片段(crc 错误)。

My issue is that the try..except is within a worker thread.我的问题是try..except在工作线程中。 This seems to cause the try..except to be ignored, and my program crashes with the CRC exception.这似乎导致try..except被忽略,并且我的程序因 CRC 异常而崩溃。

Are there any easy fixes for this issue?这个问题有什么简单的解决方法吗?

Exceptions and try..except blocks work just fine in worker threads.异常和try..except块在工作线程中工作得很好。 But accessing UI controls without proper synchronization can lead to all kinds of problems.但是在没有正确同步的情况下访问 UI 控件可能会导致各种问题。 So just don't do it.所以不要这样做。

In the context of the worker thread, load the PNG file using a local TPicture object, or better a TPNGImage object, then use TThread.Synchronize() or TThread.Notify() to Assign() that object to the TImage in the context of the main thread, eg:在工作线程的上下文中,使用本地TPicture object 或更好的TPNGImage object 加载 PNG 文件,然后使用TThread.Synchronize()TThread.Notify() Assign() ZA8CFDE6331BD59EB2AC96F 的上下文中的 ZA8CFDE6331BD59EB2AC96F 到TImage主线程,例如:

try
  PNG := TPNGImage.Create;
  try
    PNG.LoadFromFile(filename);
    TThread.Synchronize(nil,
      procedure
      begin
        Previewimage.Picture.Assign(PNG);
      end
    );
  finally
    PNG.Free;
  end;
except
  //code to handle exception
end; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM