问题描述
我正在执行一些处理器繁重的任务,每次我开始执行该命令时,我的 winform 都会冻结,直到任务完成我什至无法移动它.我使用了与微软相同的程序,但似乎没有任何改变.
i was doing some processor heavy task and every time i start executing that command my winform freezes than i cant even move it around until the task is completed. i used the same procedure from microsoft but nothing seem to be changed.
我的工作环境是带有 .net 4.5 的 Visual Studio 2012
my working environment is visual studio 2012 with .net 4.5
private async void button2_Click(object sender, EventArgs e)
{
Task<string> task = OCRengine();
rtTextArea.Text = await task;
}
private async Task<string> OCRengine()
{
using (TesseractEngine tess = new TesseractEngine(
"tessdata", "dic", EngineMode.TesseractOnly))
{
Page p = tess.Process(Pix.LoadFromFile(files[0]));
return p.GetText();
}
}
推荐答案
是的,您仍在在 UI 线程上完成所有工作.使用 async
不会自动将工作卸载到不同的线程上.你可以这样做:
Yes, you're still doing all the work on the UI thread. Using async
isn't going to automatically offload the work onto different threads. You could do this though:
private async void button2_Click(object sender, EventArgs e)
{
string file = files[0];
Task<string> task = Task.Run(() => ProcessFile(file));
rtTextArea.Text = await task;
}
private string ProcessFile(string file)
{
using (TesseractEngine tess = new TesseractEngine("tessdata", "dic",
EngineMode.TesseractOnly))
{
Page p = tess.Process(Pix.LoadFromFile(file));
return p.GetText();
}
}
使用 Task.Run
意味着 ProcessFile
(繁重的工作)在不同的线程上执行.
The use of Task.Run
will mean that ProcessFile
(the heavy piece of work) is executed on a different thread.
这篇关于如何使用异步来提高 WinForms 性能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!