【问题标题】:store image in arrayList将图像存储在 arrayList 中
【发布时间】:2011-07-08 03:40:07
【问题描述】:

这是我想要做的:线程 B 将下载一些图像并将这些图像存储在共享资源中:静态 ArrayList IMBuffer;线程 A 将从 IMBuffer 中获取图像并对其进行处理。以下是我得到的:

线程 B:

//做某事

                    System.Net.WebClient myWebClient = new System.Net.WebClient();
                   try
                      { myWebClient.DownloadFile(pth, "BufferImg"); }
                   catch
                      {  // some stuff }

                    // add new dled image to IMBuffer
                    fs = new FileStream("BufferImg", FileMode.Open, FileAccess.Read);
                    Image img = Image.FromStream(fs);
                    lock (IMBuffer)
                    { IMBuffer.Add(img); }
                    img.Dispose();

                    lock (IMRequest) { IMRequest.RemoveAt(0); }
                    myWebClient.Dispose();
                    //fs.Dispose();
                    //  File.Delete("BufferImg");

// 做点别的事情

线程 A:

// do something
Image nextImg;
                lock (IMBuffer)
                {
                    nextImg = (Image)IMBuffer[0];
                    nextImg.Save(DLedIM);
                }
// do something else

这是我遇到的问题;由于 IMBuffer 中的图像是使用文件流打开的,因此在处理流时,该行: nextImg.Save(DLedIM);导致“文件被另一个进程使用”错误。但是,如果 fs.Dispose();注释掉该行,则程序锁定“BufferImg”,结果第一次后无法将图像下载到“BufferImg”。我应该怎么做才能解决这个问题?或者有没有更简单的方法来完成我想做的事情?

【问题讨论】:

  • 在调用 fs.Dispose() 之前尝试 fs.Close()

标签: c# image arraylist filestream file-locking


【解决方案1】:

这应该可行:

byte[] buffer;
using (FileStream fs = new FileStream("BufferImg", FileMode.Open, FileAccess.Read))
{
    buffer = new byte[fs.Length];
    fs.Read(buffer, 0, (int)fs.Length);
}
using(Image img = Image.FromStream(new MemoryStream(buffer))
{
    //...
}

使用MemoryStream,您可以避免使用FileStream - 此时图像与文件完全没有任何联系,因此文件锁定应该没有任何问题。

【讨论】:

  • 谢谢 BrokenGlass,您的建议解决了这个问题。也许我完全错了,但我在这里所做的似乎有很多代码来完成一个示例任务。我不能停止想知道我是否完全错过了一些东西。 @ dthorpe 感谢您的建议,我也会查看该链接。
【解决方案2】:

与其实现自己的多线程生产者/消费者工作流程(然后必须对其进行调试),为什么不直接使用 .NET 提供的现有线程安全(不,并发)队列?可以为您节省大量的试验甚至更多的错误。

详情请看:Thread-safe blocking queue implementation on .NET

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-24
    • 2012-01-16
    • 2020-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多