Cross-thread operation not valid: accessed from a thread other than the thread it was created on.
- by user307524
Hi,
I want to remove checked items from checklistbox (winform control) in class file method which i am calling asynchronously using deletegate. but it showing me this error message:-
Cross-thread operation not valid: Control 'checkedListBox1' accessed from a thread other than the thread it was created on.
i have tried invoke required but again got the same error. Sample code is below:
private void button1_Click(object sender, EventArgs e)
{
// Create an instance of the test class.
Class1 ad = new Class1();
// Create the delegate.
AsyncMethodCaller1 caller = new AsyncMethodCaller1(ad.TestMethod1);
//callback delegate
IAsyncResult result = caller.BeginInvoke(checkedListBox1,
new AsyncCallback(CallbackMethod)," ");
}
In class file code for TestMethod1 is : -
private delegate void dlgInvoke(CheckedListBox c, Int32 str);
private void Invoke(CheckedListBox c, Int32 str)
{
if (c.InvokeRequired)
{
c.Invoke(new dlgInvoke(Invoke), c, str);
c.Items.RemoveAt(str);
}
else
{
c.Text = "";
}
}
// The method to be executed asynchronously.
public string TestMethod1(CheckedListBox chklist)
{
for (int i = 0; i < 10; i++)
{
string chkValue = chklist.CheckedItems[i].ToString();
//do some other database operation based on checked items.
Int32 index = chklist.FindString(chkValue);
Invoke(chklist, index);
}
return "";
}