简体   繁体   中英

Invoke lot of methods on UI thread from bakcground threads

Some information about my question:

I have a Windows Forms application that has a multiple thread that paralelly computing for long time. While computing these threads modifying UI elements(eg. Labels, TextBoxes, Buttons, etc.) and writing to a RichTextBox. I have a lot of delegate for thread safe calls and checking InvokeRequired a lot of times.

I have lot of methods like this:

private void AppendText(string text)
{
    if(richTextBox.InvokeRequired)
    {
        Invoke(myDelegate, new object[] { text });
    }
    else
    {
        richTextBox.Append(text);
    }
}

My question is:

Is it a good way of modifying controls on UI thread from background threads, or did I do some architectural mistakes?

Following is a simple code to explain the usage of Async-Await

public async Task Main()
{
    var result = await Background("Test");
    // Update Ui here, its on Ui thread
}

// Executed Asynchronously in the Background
public async Task<string> Background(string text)
{
    return await Task.FromResult(text);
}
  • Background method is processed asynchronously, if its over network like db call, then no thread pool thread required, if its in-memory, it will use thread pool thread
  • Once the Background method, result can be updated on the control, its automatically Ui thread
  • You may even use Task Parallel Library explicitly to process data and then update result
  • await is still a blocking call, though it will free up calling context, which means Ui will not freeze, it is still accessible, but its possible to have a non blocking call using Task.Run , which when returns can be used to update the Ui, though you always have to prevent Main / Ui thread from exiting

Edit 1 (Async Button Click Event)

public async void Button1_Click(object sender,EventArgs e)
{
   await (Async Method Call)
   // Update Ui
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM