everyone,
I have a problem with handling an async task.
I have a timer and separately in a async Task, I wanted to run a state machine. Depending on what time is current, I wanted to run a status and write it to a label to display on the windows form.
I got the error System.InvalidOperationException - Invalid cross-thread operation.
private async void btnStart_Click(object sender, EventArgs e)
{
labelTimer.Text = mytimer.ToString(@"hh\:mm\:ss");
// Timer Start
timer1.Start();
// Start StateMachine
try
{
await stateMachine();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private async Task stateMachine()
{
await Task.Run(() =>
{
while (sMachine)
{
switch(labelTimer.Text)
{
case "00:00:55":
labelConsole.Text = "Works";
break;
}
}
});
}
Does anyone have an idea how I can write to the Windows form from an async task?
CodePudding user response:
When you use Task.Run, you're pushing work to a non-UI thread; a non-UI thread cannot talk to to the UI - you need to get back to the UI for that; so instead of labelConsole.Text = "Works";, you'd need to do something like
Invoke((MethodInvoker)delegate{
labelConsole.Text = "Works";
});
Note, however, that you'd also probably want a pause of some kind - you don't want to loop aggressively millions of times a second.
