C#在删除文件之前等待操作完成

时间:2017-12-03 19:20:57

标签: c#

我的删除调用不起作用,因为调用时目录中的文件是只读的(仍在访问)。如何等待tesseract引擎处理和释放文件以将其删除?

我在“删除”调用中尝试了一个while循环,等待异常不被抛出 - 这只是挂起。我见过使用Tasks,Threads和Processes的例子。什么是编程方式正确的方法来做到这一点?

        // create a subdirectory called processing
        Directory.CreateDirectory(dir + "//processing");
        string directory = dir + "//processing";

        // extract the images to the processing directory
        ImageExtractor.ExtractImagesFromFile(LongName, "img", directory, true);

        // extract the text from all the files in processing
        string[] images = Directory.GetFiles(directory);
        foreach (string file in images)
        {
            Bitmap image = new Bitmap(file);
            using (TesseractEngine engine = new TesseractEngine(@"./tessdata", "eng", EngineMode.Default))
            {
                using(var img = PixConverter.ToPix(image))
                {
                    using(var page = engine.Process(img))
                    {
                        fileContent = fileContent + " " + page.GetText();
                    }
                }
            }
        }

        Directory.Delete(dir + "//processing", true);

使用任务......(对我不起作用)......

Task t = Task.Run(() => { 
            foreach (string file in images)
            {
                Bitmap image = new Bitmap(file);
                using (TesseractEngine engine = new TesseractEngine(@"./tessdata", "eng", EngineMode.Default))
                {
                    using(var img = PixConverter.ToPix(image))
                    {
                        using(var page = engine.Process(img))
                        {
                            fileContent = fileContent + " " + page.GetText();
                        }
                    }
                }
            }
            });

            t.Wait();

            Directory.Delete(dir + "//processing", true);

0 个答案:

没有答案