我想在类文件方法中从checklistbox(winform控件)中删除已检查的项目,我使用deletegate异步调用。但它显示了这个错误信息: -
跨线程操作无效:控制'checkedListBox1'从其创建的线程以外的线程访问。
我已经尝试过调用,但又遇到了同样的错误。示例代码如下:
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)," ");
}
在TestMethod1的类文件代码中: -
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 "";
}
答案 0 :(得分:1)
您确定没有从这行代码中收到错误吗?
string chkValue = chklist.CheckedItems[i].ToString();