所以我使用C#和Forms,我有ListView和 Items ,我試圖找到 Item 和 text。
我在 2 個單獨的腳本/類中有單獨的執行緒(1. MainForm.cs 和 2. workWithLists.cs 我需要在 workWithLists.cs 中使用 FindItemWithText)所以我需要使用invoke:
ListViewItem v = listView1.Invoke(listView1.FindItemWithText("TestName"));
但是當我將Invoke 與 FindItemWithText 一起使用時出現錯誤:
Cannot convert from "System.Windows.Forms.ListViewItem" to "System.Delegate"
沒有 呼叫:
ListViewItem v = listView1.FindItemWithText("TestName");
我沒有任何錯誤,但是當我運行代碼時,它給了我錯誤:
Invalid multi-thread operation: An attempt was made to access control 'listView1' from a thread other than the thread it was created on.
請有人向我解釋我做錯了什么,以及如何解決這個問題。
從執行緒 listview1 呼叫 FindItemWithText 不是答案 :D
編輯:我在 MainForm.cs 中有這段代碼:
public static ListView list;
public delegate void FindInListViewDelegate(string name);
public FindInListViewDelegate FindInListView = new FindInListViewDelegate(Find);
public ListViewItem Find(string name)
{
ListViewItem item = list.FindItemWithText(name);
return item;
}
但我收到錯誤:A field initializer cannot reference the non-static field, method, or property 'MainForm.Find(string)'
我正在改變:
public ListViewItem Find(string name) {}
到:
public static ListViewItem Find(string name) {}
但隨后它給出了另一個錯誤:'ListViewItem MainForm.Find(string)' has the wrong return type
uj5u.com熱心網友回復:
Control.Invoke 方法,在擁有控制元件的基礎視窗句柄的執行緒上執行委托。
并且 listView1.FindItemWithText 不是委托,因此在您的主執行緒中宣告一個 Action 或委托并在您的第二個執行緒中使用它。
主執行緒:
public delegate void FindInListViewDelegate(string name);
public FindInListViewDelegate FindInListView = new FindInListViewDelegate(Find);
public ListViewItem Find(string name)
{
var item = listView1.FindItemWitdhText(name);
...
}
次要執行緒:
myForm.Invoke(myForm.FindInListView, new object[] { nameToSearch });
您也可以使用 Action,我設定了一個小型控制臺應用程式:
internal class Program
{
static public Action<string> FindInListView = (name) =>
{
Console.WriteLine($"Finding item {name} in ListView");
};
static async Task Main(string[] args)
{
await new TaskFactory().StartNew(() => { FindInListView.Invoke("Joan"); });
return;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/474151.html
下一篇:反應鉤子形式如何檢查郵件是否相等
