Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
613 views
in Technique[技术] by (71.8m points)

c# - How can I use async to increase WinForms performance?

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();
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...