How can I use async to increase WinForms performance?

前端 未结 2 1131
轻奢々
轻奢々 2020-11-30 00:01

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 th

相关标签:
2条回答
  • 2020-11-30 00:29

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

    See these for your reference:

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

    Start thread with parameters

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题