更新时间:2023-11-15 13:31:58
是的,你仍然在做UI线程上的所有工作的 的。使用异步
是不会自动卸载工作到不同的线程。你可以这样做,但:
专用异步无效button2_Click(对象发件人,EventArgs的发送)
{
字符串文件=文件[0];
任务<串GT;任务= Task.Run(()=> ProcessFile(文件));
rtTextArea.Text =等待任务;
}私人字符串ProcessFile(字符串文件)
{
使用(TesseractEngine苔丝=新TesseractEngine(tessdata,DIC
EngineMode.TesseractOnly))
{
网页P = tess.Process(Pix.LoadFromFile(文件));
返回p.GetText();
}
}
使用 Task.Run
将意味着 ProcessFile
(沉重的工作片)是在执行不同的主题。
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.
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();
}
}
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();
}
}
The use of Task.Run
will mean that ProcessFile
(the heavy piece of work) is executed on a different thread.