C# 如何使用异步来提高 WinForms 的性能?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14962969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:34:30  来源:igfitidea点击:

How can I use async to increase WinForms performance?

c#asynchronoustesseract

提问by Serak Shiferaw

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.

我正在执行一些处理器繁重的任务,每次我开始执行该命令时,我的 winform 都会冻结,直到任务完成之前我什至无法移动它。我使用了微软的相同程序,但似乎没有任何改变。

my working environment is visual studio 2012 with .net 4.5

我的工作环境是带有 .net 4.5 的 Visual Studio 2012

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();
    }
}

采纳答案by Jon Skeet

Yes, you're still doing all the work on the UI thread. Using asyncisn't going to automatically offload the work onto different threads. You could do this though:

是的,您仍然在 UI 线程上完成所有工作。使用async不会自动将工作卸载到不同的线程上。你可以这样做:

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.Runwill mean that ProcessFile(the heavy piece of work) is executed on a different thread.

使用Task.Runwill 意味着ProcessFile(繁重的工作)在不同的线程上执行。

回答by David Smithers

You can also do this by starting your task in new thread. Just use Thread.Start or Thread. ParameterizedThreadStart

您也可以通过在新线程中开始您的任务来做到这一点。只需使用 Thread.Start 或 Thread。参数化线程开始

See these for your reference:

请参阅以下内容以供参考:

http://msdn.microsoft.com/en-us/library/system.threading.parameterizedthreadstart.aspx

http://msdn.microsoft.com/en-us/library/system.threading.parameterizedthreadstart.aspx

Start thread with parameters

带参数启动线程