开发者

Cross-thread operation not valid: accessed from a thread other than the thread it was created on

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(CheckedLis开发者_运维知识库tBox 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 "";
}


Are you sure you are not getting the error from this line of code?

string chkValue = chklist.CheckedItems[i].ToString();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜