方法1:
使用調用像蒂格蘭描述。
對於此的WinForms會是什麼樣子:
Thread t = new Thread(() =>
{
if (!Dispatcher.CurrentDispatcher.CheckAccess())
{
Dispatcher.CurrentDispatcher.BeginInvoke(
new Action(() =>
{
foreach (ListViewItem row in listView1.Items)
{
row.SubItems[0].Text = "Checking";
Thread.Sleep(2000);
}
}),
DispatcherPriority.ApplicationIdle,
null);
}
else
{
foreach (ListViewItem row in listView1.Items)
{
row.SubItems[0].Text = "Checking";
Thread.Sleep(2000);
}
}
});
t.Start();
的的checkAccess()如果從UI線程否則爲false稱爲調用返回true。
Dispatcher類位於「WindowsBase」NET中的「System.Windows.Threading」命名空間中。 https://stackoverflow.com/a/4429009/1469035
編輯:大會
調度信息從複製更改代碼的WinForms。 編輯:代碼固定。
方法2:
使用回調:
未經測試的代碼:從除UI線程其他線程控制
public partial class Form1 : Form
{
private delegate void SetCallback(ListViewItem row, string text);
public Form1()
{
InitializeComponent();
}
private void SomeMethod()
{
Thread t = new Thread(() =>
{
foreach (ListViewItem row in listView1.Items)
{
if (listView1.InvokeRequired)
{
SetCallback d = new SetCallback(SetText);
this.Invoke(d, new object[] { row, "Checking" });
}
Thread.Sleep(2000);
}
});
t.Start();
}
private void SetText(ListViewItem row, string text)
{
row.SubItems[0].Text = text;
}
}
AFAIK只讀訪問被允許的WinForms。所以你可以檢查你想要的任何Control-Property,並將所需的信息傳遞給Delegate。
即使閱讀工具以這種方式工作,您也可以創建另一個具有返回值的委託。該invoke()方法返回一個對象:
與此類似:
private delegate object GetCallback(ListViewItem row);
private object o;
...
GetCallback g = new GetCallback(GetText);
o = this.Invoke(g, new object[] { row });
private string GetText(ListViewItem row)
{
return row.SubItems[0].Text;
}
來源於:Link
我一直髮現我並不真正需要訪問控制交叉線程,thread.sleep也幾乎不是一個好主意。你試圖完成什麼? – Sayse
使用調度程序http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.aspx – wudzik
只要確保'listView1'是一個全局變量。 –