Reputation: 11464
When I acces Form controls within BackgroundWorker
DoWork
event, it reads values from DatePicker but not from TextBox or ComboBox
Error:
Cross-thread operation not valid: Control 'cmbProgram' accessed from a thread other than the thread it was created on.
Code :
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
string strDate = dtpDate.Value.ToString();
string strProgram = cmbProgram.Text;
}
How does it read values from DataPicker (in a different thread)?
Is there any workaround to access Form Controls from BackgroundWorker
DoWork
Event?
Upvotes: 1
Views: 3194
Reputation: 3904
You can pass it as an argument. For example:
backgroundworker1.RunWorkerAsync(comboBox1.SelectedItem.ToString());
And grab the contents in the doWork
with
string Item = e.Argument.ToString();
Upvotes: 1
Reputation: 1728
Use:
Dispatcher.Invoke(new Action(() =>
{
string strDate = dtpDate.Value.ToString();
string strProgram = cmbProgram.Text;
}));
Upvotes: 2
Reputation: 6269
You cannot access a control from a different thred. The usual way of getting around that problem is to read the current value from the UI thread, and then pass the value to the second thread (or BackgroundWorker).
You can disable the check by setting CheckForIllegalCrossThreadCalls on the control class to false, but be advised you don't want to do this.
Upvotes: 2