C# WinForm provides Background Worker Control that is capable of run asynchronous job in background. This must be ideal for fetching data in the background .
What about updating UI from background ? Like update a listview items from database . Let’s begin from setup.
How to ?
The Background Worker control has a event ,DoWork where we can add our background tasks.
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// logic here
}
We can use the RunWorkerCompleted to apply logic which will executed after completion.
In the form load event (or from any event ) you can start the task by running
this.backgroundWorker1.RunWorkerAsync();
Problem with UI and Worker
When you try to access a component in the UI from a Background Worker DoWork event, may end up like this.
System.InvalidOperationException: ‘Cross-thread operation not valid: Control ‘listView1’ accessed from a thread other than the thread it was created on…
Solution
To bypass this error C#.Net provides invoke method which execute the delegate specified.
To add items to the listview from a background worker I used the following code snippet which uses a MethodInvoker and a delegate
try
{
listView1.Invoke(new MethodInvoker(
delegate
{
item = new ListViewItem("");
item.SubItems.Add(new ListViewItem.ListViewSubItem(item, "Some Column Value Here"));
listView1.Items.Add(item);
}
));
}
catch (Exception)
{
throw;
}
I hope this will help you and recommend the following snippets.
- Task with parameters in C#
- Connection string for MSQL Server local database
- Quilljs mention snippet
- Categorize user control properties in C#
- Add properties to user control in C#
- How to update Listview from Background Worker in WinForm-C#.Net ?
- How to draw a line below textbox using Pen in C#
- How to draw a rectangle around textbox in C#
- Python : list to tuple
- Flutter Search Widget