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

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

问题描述

我在做一些处理繁重的任务我每次开始执行该命令我的winform冻结,直到比任务完成,我不能甚至移动它的时间。 i。从微软但没有似乎要改变使用的相同的方法

我的工作环境的Visual Studio 2012与.NET 4.5

 专用异步无效button2_Click(对象发件人,EventArgs的发送)
{
    任务<串GT;任务= OCRengine();
    rtTextArea.Text =等待任务;
}私人异步任务<串GT; OCRengine()
{
    使用(TesseractEngine苔丝=新TesseractEngine(
           tessdata,DIC,EngineMode.TesseractOnly))
    {
        网页P = tess.Process(Pix.LoadFromFile(文件[0]));
        返回p.GetText();
    }
}


解决方案

是的,你仍然在做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.

这篇关于如何使用异步来提高性能的WinForms?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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