c# 如何设置代码在finally运行

发布于 2024-10-31 17:50:34 字数 3389 浏览 1 评论 0原文

我需要将代码行设置为在一切完成运行后运行。有人知道该怎么做吗?

private void ScanBT_Click(object sender, EventArgs e)
        {
            var folder = @"C:\Users\Shen\Desktop\LenzOCR\LenzOCR\WindowsFormsApplication1\ImageFile";

            DirectoryInfo directoryInfo;
            FileInfo[] files;
            directoryInfo = new DirectoryInfo(folder);
            files = directoryInfo.GetFiles("*.jpg", SearchOption.AllDirectories);

            var processImagesDelegate = new ProcessImagesDelegate(ProcessImages2);
            processImagesDelegate.BeginInvoke(files, null, null);


            **//HERE IS THE LINE OF CODE THAT NEED TO BE RUN AFTER EVERYTHING FINISH RUN
            System.IO.File.Delete(@"C:\Users\Shen\Desktop\LenzOCR\TempFolder\tempPic.jpg");**
        }

        private void ProcessImages2(FileInfo[] files)
        {
            var comparableImages = new List<ComparableImage>();

            var index = 0x0;

            foreach (var file in files)
            {
                if (exit)
                {
                    return;
                }

                var comparableImage = new ComparableImage(file);
                comparableImages.Add(comparableImage);
                index++;
            }

            index = 0;

            similarityImagesSorted = new List<SimilarityImages>();
            //MessageBox.Show("here"+singleFileInfo.FullName);
            var fileImage = new ComparableImage(singleFileInfo);

            for (var i = 0; i < comparableImages.Count; i++)
            {
                if (exit)
                    return;

                var destination = comparableImages[i];
                var similarity = fileImage.CalculateSimilarity(destination);
                var sim = new SimilarityImages(fileImage, destination, similarity);
                similarityImagesSorted.Add(sim);
                index++;
            }

            similarityImagesSorted.Sort();
            similarityImagesSorted.Reverse();
            similarityImages = new BindingList<SimilarityImages>(similarityImagesSorted);

            var buttons =
                new List<Button>
                    {
                        ScanBT
                    };

            if (similarityImages[0].Similarity > 70)
            {
                con = new System.Data.SqlClient.SqlConnection();
                con.ConnectionString = "Data Source=SHEN-PC\\SQLEXPRESS;Initial Catalog=CharacterImage;Integrated Security=True";
                con.Open();

                String getFile = "SELECT ImageName, Character FROM CharacterImage WHERE ImageName='" + similarityImages[0].Destination.ToString() + "'";
                SqlCommand cmd2 = new SqlCommand(getFile, con);
                SqlDataReader rd2 = cmd2.ExecuteReader();

                while (rd2.Read())
                {
                    for (int i = 0; i < 1; i++)
                    {
                        string getText = rd2["Character"].ToString();
                        Action showText = () => ocrTB.AppendText(getText);
                        ocrTB.Invoke(showText);
                    }
                }
                con.Close();
            }
            else
            {
                MessageBox.Show("No character found!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }


        }

I need to set the line of code to run after everything has finish run. Anyone know how to do that?

private void ScanBT_Click(object sender, EventArgs e)
        {
            var folder = @"C:\Users\Shen\Desktop\LenzOCR\LenzOCR\WindowsFormsApplication1\ImageFile";

            DirectoryInfo directoryInfo;
            FileInfo[] files;
            directoryInfo = new DirectoryInfo(folder);
            files = directoryInfo.GetFiles("*.jpg", SearchOption.AllDirectories);

            var processImagesDelegate = new ProcessImagesDelegate(ProcessImages2);
            processImagesDelegate.BeginInvoke(files, null, null);


            **//HERE IS THE LINE OF CODE THAT NEED TO BE RUN AFTER EVERYTHING FINISH RUN
            System.IO.File.Delete(@"C:\Users\Shen\Desktop\LenzOCR\TempFolder\tempPic.jpg");**
        }

        private void ProcessImages2(FileInfo[] files)
        {
            var comparableImages = new List<ComparableImage>();

            var index = 0x0;

            foreach (var file in files)
            {
                if (exit)
                {
                    return;
                }

                var comparableImage = new ComparableImage(file);
                comparableImages.Add(comparableImage);
                index++;
            }

            index = 0;

            similarityImagesSorted = new List<SimilarityImages>();
            //MessageBox.Show("here"+singleFileInfo.FullName);
            var fileImage = new ComparableImage(singleFileInfo);

            for (var i = 0; i < comparableImages.Count; i++)
            {
                if (exit)
                    return;

                var destination = comparableImages[i];
                var similarity = fileImage.CalculateSimilarity(destination);
                var sim = new SimilarityImages(fileImage, destination, similarity);
                similarityImagesSorted.Add(sim);
                index++;
            }

            similarityImagesSorted.Sort();
            similarityImagesSorted.Reverse();
            similarityImages = new BindingList<SimilarityImages>(similarityImagesSorted);

            var buttons =
                new List<Button>
                    {
                        ScanBT
                    };

            if (similarityImages[0].Similarity > 70)
            {
                con = new System.Data.SqlClient.SqlConnection();
                con.ConnectionString = "Data Source=SHEN-PC\\SQLEXPRESS;Initial Catalog=CharacterImage;Integrated Security=True";
                con.Open();

                String getFile = "SELECT ImageName, Character FROM CharacterImage WHERE ImageName='" + similarityImages[0].Destination.ToString() + "'";
                SqlCommand cmd2 = new SqlCommand(getFile, con);
                SqlDataReader rd2 = cmd2.ExecuteReader();

                while (rd2.Read())
                {
                    for (int i = 0; i < 1; i++)
                    {
                        string getText = rd2["Character"].ToString();
                        Action showText = () => ocrTB.AppendText(getText);
                        ocrTB.Invoke(showText);
                    }
                }
                con.Close();
            }
            else
            {
                MessageBox.Show("No character found!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }


        }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

猫烠⑼条掵仅有一顆心 2024-11-07 17:50:34

将删除文件的代码行移动到 process images 方法的末尾怎么样?

How about move the line of code to delete the file to the end of the process images method?

摘星┃星的人 2024-11-07 17:50:34
  • BackgroundWorker.DoWork(...) 中运行 ProcessImages2 方法内的代码
  • ProcessImagesDelegate.BeginInvoke(files, null, null) 替换为 worker.RunWorkerAsync(。 ..)
  • 捕获事件 RunWorkerCompleted 并执行 File.Delete(...)

通过这种方式,您的主线程可以由最终用户自由刷新和使用。

  • Run the code inside ProcessImages2 method in a BackgroundWorker.DoWork(...)
  • Substitute ProcessImagesDelegate.BeginInvoke(files, null, null) with worker.RunWorkerAsync(...)
  • Trap the event RunWorkerCompleted and execute there the File.Delete(...).

In this way your main thread is free to be refreshed and used by end-user.

紙鸢 2024-11-07 17:50:34

如果您像下面这样编辑方法,则调用将阻塞,直到 ProcessImages2 完成。

var processImagesDelegate = new ProcessImagesDelegate(ProcessImages2);  
IAsyncResult result = processImagesDelegate.BeginInvoke(files, null, null);
result.AsyncWaitHandle.WaitOne();
**//HERE IS THE LINE OF CODE THAT NEED TO BE RUN AFTER EVERYTHING FINISH RUN   
System.IO.File.Delete(@"C:\Users\Shen\Desktop\LenzOCR\TempFolder\tempPic.jpg");  

If you edit the method like below the call will block until ProcessImages2 is completed.

var processImagesDelegate = new ProcessImagesDelegate(ProcessImages2);  
IAsyncResult result = processImagesDelegate.BeginInvoke(files, null, null);
result.AsyncWaitHandle.WaitOne();
**//HERE IS THE LINE OF CODE THAT NEED TO BE RUN AFTER EVERYTHING FINISH RUN   
System.IO.File.Delete(@"C:\Users\Shen\Desktop\LenzOCR\TempFolder\tempPic.jpg");  
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文