My Textbox does not change when inside Task.Run
I use C# Winforms
I am using Task.Run()
in order to get my WinForm does not freeze.
Inside this code, I need to update the textbox text.
I tried to update textbox text directly and through Invoke but non worked.
I tried to minimize my code to just focus on the problem
Any idea how to update the text box inside Task.Run()
?
public async void MyFunction()
{
await Task.Run(() =>
{
lvwFiles.BeginInvoke(new Action(() =>
{
foreach (ListViewItem item in this.lvwFiles.Items)
{
txtLog.Text = item.Text + "\r\n" +txtLog.Text;
if (txtLog.InvokeRequired)
{
txtLog.Invoke(new MethodInvoker(delegate { txtLog.Text = item.Text + "\r\n" + txtLog.Text; }));
}
Thread.Sleep(4000);
item.BackColor = Color.FromArgb(128, 255, 128);
}
}));
});
}
Solution 1:
You're using Task.Run
to run it in a different thread, but then you're using BeginInvoke
, which tells it to run that code on the UI thread. So the result is that your code is run on the UI thread. And since you're using Thread.Sleep()
, you lock your UI thread.
Instead, run it all on your UI thread and use Task.Delay()
instead of Thread.Sleep()
to avoid locking the UI thread.
public async void MyFunction()
{
foreach (ListViewItem item in this.lvwFiles.Items)
{
txtLog.Text = item.Text + "\r\n" + txtLog.Text;
await Task.Delay(4000);
item.BackColor = Color.FromArgb(128, 255, 128);
}
}