异步方法有时永远不会结束

时间:2013-08-09 00:09:35

标签: c# task .net-4.5 async-await

我正在拍照并处理它们。 然后我试图将位图(这些图像)保存在文件中。

例如

  • 我拍摄“沙漠”和“花朵”图像,我每次异步处理它们4次。
  • 然后我调用(等待)8次saveAsync()方法来保存它们。

    • 所发生的事情是desert_modified和flower_modified,flower_modified(1),flower_modified(2),flower_modified(3)被保存。
    • 没有图像desert_modified(1),desert_modified(2),desert_modified(3)。

要保存它们的方法永远不会完成。有什么建议吗?

async private Task saveAsync(Bitmap bitmap, String path, String fileName, int requestNo)
{
    int temp = 1;
    String pth = path;
    String fileName1 = fileName;
    try
    {
        await Task.Run(() =>
            {

                if (File.Exists(pth))
                {

                    String[] array = fileName1.Split('.');
                    String modifiedFileName = array[0] + "_modified" + "(" + temp + ")." + array[1];
                    pth = fullPath.Replace(fileName1, modifiedFileName);

                    while (File.Exists(pth))
                    {
                        temp++;
                        //array = fileName.Split('.');
                        modifiedFileName = array[0] + "_modified" + "(" + temp + ")." + array[1];
                        pth = fullPath.Replace(fileName1, modifiedFileName);

                    }

                    bitmap.Save(@pth);

                }
                else
                {
                    bitmap.Save(@pth);
                }
                bitmap.Dispose();
            });

    }
    catch (Exception ex)
    {
        outputTextBox2.Text += ex.InnerException.Message;
    }
}

2 个答案:

答案 0 :(得分:2)

您使用String.Replace,这实际上不合适。 我认为您的代码中的主要错误是您尝试在while循环中替换fileName1中的pth尽管 fileName1 出现在pth中,因为它在while循环之前被修改了。 因此pth永远不会在while循环中更改,这就是while循环永不结束的原因。

要解决此问题,请使用pth = fullPath.Replace(pth, modifiedFileName) ,我建议使用pth = modifiedFileName

无论如何,使用Replace不会保存任何内存,因为C#中的字符串以及许多其他语言中的字符串是不可变的!因此,即使按Replace,也会生成一个新的String。

编辑: ......嗯......也许这个答案并不完全正确,因为另一方面你正在处理fullPath 但是fullPath未在此函数中定义:) ..这甚至来自哪里?

答案 1 :(得分:2)

如果您对我在评论中暗示的改进代码感兴趣,那么这是一个开始:

如你所见,这个

  • 删除(混淆命名的)局部变量,例如pthfileName1modifiedFileName
  • 不再滥用 Split(错误地)剖析路径(如果目录有扩展名怎么办?如果文件名本身包含.怎么办?)
  • 使用PathCombine获取正确的路径分隔符
  • 使用固定格式字符串轻松生成候选文件名
  • 使用单个do-while循环,而不是复制生成文件名的行

总的来说,我认为这是很多更简单。

await Task.Run(() =>
  {
      var fmt = Path.Combine(path, Path.GetFileNameWithoutExtension(fileName)) + "_modified{0}" + Path.GetExtension(fileName);

      int counter = 1;
      string newName;
      do {
          newName = string.Format(fmt, counter++);
      }
      while (File.Exists(newName));

      using (bitmap)
          bitmap.Save(newName);
  });

我在本地PC上制作了一个简单的独立测试程序,所以我可以对它进行测试:

using System.IO;
using System;

public class X
{
    public class Bitmap : IDisposable { 
        public void Dispose() { } 
        public void Save(string location)
        {
            Console.WriteLine("Saving: {0}", location);
            using (var s = new StreamWriter(location))
                s.WriteLine("hello world");
        }
    }

    private static void saveAsync(Bitmap bitmap, String path, String fileName, int requestNo)
    {
        Action a = () =>
          {
              var fmt = Path.Combine(path, Path.GetFileNameWithoutExtension(fileName)) + "_modified{0}" + Path.GetExtension(fileName);

              int counter = 1;
              string newName;
              do {
                  newName = string.Format(fmt, counter++);
              }
              while (File.Exists(newName));

              using (bitmap)
                  bitmap.Save(newName);
          };

        a();
        a();
        a();
        a();
    }

    public static void Main()
    {
        saveAsync(new Bitmap(), "/tmp", "foo.png", 3);
    }
}

打印

Saving: /tmp/foo_modified1.png
Saving: /tmp/foo_modified2.png
Saving: /tmp/foo_modified3.png
Saving: /tmp/foo_modified4.png