0
我想在類文件方法中使用deletegate從異步調用的checklistbox(winform控件)中移除checked項。但它向我顯示了以下錯誤消息: -跨線程操作無效:從其創建線程以外的其他線程訪問
跨線程操作無效:從其創建的線程以外的線程訪問控件'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 "";
}
是的,我確信這一點。 – user307524 2010-04-03 09:56:03