在我的应用程序的图像预加载缓存,还有通过它,用户可以一步图像列表。图像加载速度很慢,因此为了改善用户体验,我希望在背景中预加载一些图像(例如,列表中的图像在当前选定的图像之后)。C# - 如何实现与线程
我从来没有真正使用的线程在C#,所以我要寻找某种“最佳实践”的建议如何实现以下行为:
public Image LoadCachedImage(string path)
{
// check if the cache (being operated in the background)
// has preloaded the image
Image result = TryGetFromCache(path);
if (result == null) { result = LoadSynchronously(path); }
// somehow get a list of images that should be preloaded,
// e.g. the successors in the list
string[] candidates = GetCandidates(path);
// trigger loading of "candidates" in the background, so they will
// be in the cache when queried later
EnqueueForPreloading(candidates);
return result;
}
我相信,一个后台线程应该是监控队列,并连续处理通过EnqueueForPreloading()发布的元素。我想知道如何实现后台工作线程的这个“主循环”(或者也许有更好的方法来做到这一点?)
BeginInvoke不会对“在不同的线程上”做任何事情。相反,它让你在UI线程上专门做一些事情。它基本上说“下一次UI线程不忙于做其他事情时,在UI线程上调用此方法”。当您的调用方法在UI线程上执行时,UI线程无法做其他事情 - 它看起来没有反应。所以......你的第一个建议可以正常工作,但第二个建议不会。 – 2011-05-06 03:22:44