c#如何设置代码在最后运行
本文关键字:代码 最后 运行 设置 何设置 | 更新日期: 2023-09-27 17:49:37
我需要将代码行设置为在所有内容完成运行后运行。有人知道怎么做吗?
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);
}
}
如何将删除文件的代码行移动到进程图像方法的末尾?
- 运行ProcessImages2方法中的代码在BackgroundWorker.DoWork(…)
- 替换 ProcessImagesDelegate。BeginInvoke(files, null, null) with worker.RunWorkerAsync(…)
- 捕获事件RunWorkerCompleted并在那里执行File.Delete(…).
这样的话,你的主线程就可以被刷新并被最终用户使用。
如果像下面这样编辑方法,调用将阻塞,直到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");