【发布时间】:2019-10-13 12:23:25
【问题描述】:
我想在 Unity 中从磁盘加载一堆图像。所以我想使用线程池在辅助线程中实际加载图像字节,然后在主线程中应用纹理。
我创建了一个函数,它获取路径作为输入并在System.Threading.ThreadPool.QueueUserWorkItem 的帮助下加载图像字节,当它完成时,它调用一个回调,从这些字节中创建纹理并将其应用于游戏对象。
我遇到的问题是回调是使用工作线程的亲和性执行的。并且统一不允许非主线程对其数据进行修改。
有没有办法在主线程的关联中执行回调?
这是相关代码:
public delegate void OnBytesLoaded(byte[] bytes);
private void LoadBytesToTexture(byte[] bytes)
{
Texture2D texture = new Texture2D(100, 100);
texture.LoadImage(bytes);
thumbnail.texture = texture;
}
private void LoadTextureImage(string imagePath)
{
OnBytesLoaded callback = new OnBytesLoaded(LoadBytesToTexture);
System.Threading.ThreadPool.QueueUserWorkItem(o =>
{
byte[] bytes = System.IO.File.ReadAllBytes(imagePath);
Debug.Log($"Loaded image bytes");
callback?.Invoke(bytes);
});
}
正如我所说,我的问题是LoadBytesToTexture 是在线程池线程的亲和中执行的,而不是主线程。
【问题讨论】:
-
@mjwills 有人说:“从 MyMethod 中调用
Control.Invoke以将委托的执行编组到 UI 线程上”。这正是我正在做的。虽然委托仍然没有在主线程上执行。 -
@mjwills
callback?.Invoke(bytes); -
callback?.Invoke(bytes);中的Invoke是a compiler-generated method。和Control.Invoke不一样。 -
@Theodor Zoulias 我明白了。虽然
Control.Invoke似乎与我无关,因为它是寡妇表格的一部分。
标签: c# multithreading unity3d