方法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'是一个全局变量。 –