如何使用异步来提高 WinForms 性能? [英] How can I use async to increase WinForms performance?

查看:30
本文介绍了如何使用异步来提高 WinForms 性能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在执行一些处理器繁重的任务,每次我开始执行该命令时,我的 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 性能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆