Reputation: 581
My WinForm application invokes a thread to run a process, and also starts a WinForms Timer control Tick event at same time to display the progress of the thread process.
public void threadTimer_Tick(object sender, EventArgs e)
{
lblProgessCount.Text = countDownText;
}
countDownText
is a static string variable which is get updated from the thread process and time to time I want to display the latest value in it in a UI label control. But it gives me the below error,
Cross-thread operation not valid: Control 'lblProgressCount' accessed from a thread other than the thread it was created on.
But the timer is started outside the thread process. Can anyone explain how to solve this issue.
Upvotes: 0
Views: 94
Reputation: 1039438
But the timer is started outside the thread process.
But you are manipulating the UI inside the timer callback. Here you are attempting to modify the UI from a different thread:
lblProgessCount.Text = ...
You should use the Invoke
method to ensure that this action is marshaled to the main UI thread:
public void threadTimer_Tick(object sender, EventArgs e)
{
Action setValue = () => lblProgessCount.Text = countDownText;
this.Invoke(setValue);
}
Upvotes: 2