【发布时间】:2016-06-24 18:29:19
【问题描述】:
如果尚未保存特定 bmp 图像,则此方法应返回将特定 bmp 图像保存到磁盘的任务。
我有一个名为 CachedTileTasks 的 ConcurrentDictionary,它使用图像信息作为键来缓存已经完成的任务。基本上,我不想启动保存已保存图像的任务。
我遇到的问题是任务永远不会被创建,并且代码一旦开始尝试创建任务就会停止。这个方法被调用了 9 次,因为那里有 9 个请求进入 - 所有线程都被搁置在这里。
它编译没有错误并且不会抛出任何异常。我的代码(重命名了一些变量)如下:
internal Task SaveImage(String imgFilePath, int encodedImageInfo)
{
Debug.WriteLine("SaveImage called"); // this is being printed
var imageKey = MakeImageKey(encodedImageInfo);
Task saveImageToDiskTask = null;
var foundTask = CachedTileTasks.TryGetValue(imageKey, out saveImageToDiskTask);
// if the task has been cached, it should be copied into saveImageToDiskTask
// if not, the task should remain null
if (foundTask) // you have already done this task
{
// if you've already saved the image to disk, we don't want to return a real task
// so when we execute it, it doesn't take up extra time repeating a task
return null;
}
else // you have not yet done this task, and saveImageToDiskTask should be null
{
// creates image we want to save
var img = new WriteableBitmap(new Uri(imgFilePath));
// this is the last line that it reaches
saveImageToDiskTask = new Task(() =>
{
Debug.WriteLine("Creating the task."); // NOT PRINTING
new ImageExporter().SaveToDisk(img, scale,
TileSize, saveAt, pageNum, user);
Debug.WriteLine("Tiles have been saved to disk.");
});
// cache the task
CachedTileTasks.GetOrAdd(imageKey, saveImageToDiskTask);
// return it
return saveImageToDiskTask;
}
}
我查看了 StackOverflow 和 msdn 文档,但没有任何结果(如果重复,我深表歉意)。知道发生了什么吗?
【问题讨论】:
-
这个方法怎么称呼?你怎么知道“任务永远不会被创建”?
-
SaveToDisk 是异步的吗?
-
该任务后来由一个调用 SaveImage 的函数创建,但它没有被启动,只是等待。我添加了两行: saveImageTask = SaveImage(imgFilePath, imageInfo); saveImageTask.Start();,所以spender的问题实际上让我弄清楚了。
标签: c# asp.net multithreading task msdn