您好,
Im目前正在编写服务器监视应用程序。
班级
public class Server
{
public string SERVERNAME;
public string ENVIRONMENT;
public string VERSION;
public string CPU_PERCETAGE;
public string CPU_NAME;
public string CPU_DESCRIPTION;
public string CPU_VOLTAGE;
}
我当前在主窗口中有一个页面,我可以在其中执行并填充数据:
方法
try
{
{
Thread test = new Thread(() =>
{
datagrid_Disks.Dispatcher.BeginInvoke(
new Action(() =>
{
datagrid_Disks.ItemsSource = Server.GetDisksInfo(textbox_Username.Text,
textbox_password.Password,
textbox_IP.Text,
textbox_Domain.Text);
}));
});
test.Start();
}
catch (UnauthorizedAccessException)
{
Worker.ShowModernBox("Onjuiste gebruiksersnaam" + Environment.NewLine + "of wachtwoord.");
}
catch (ManagementException)
{
Worker.ShowModernBox("Server geeft geen Response." + Environment.NewLine + "Controleer Aub de instelling.");
}
问题
我的mainThread等待线程完成,似乎无法弄清楚为什么会发生这种情况。
所有帮助表示赞赏!
问题在于Dispatcher.Invoke阻止了UI线程,因此任何线程Invoke
都应尽可能小。
将您耗时的代码放在调用之外,以解决问题。
正如@RohitVals指出的那样,您无法从后台线程访问UI控件,因此您将不得不使用2次调用-一个调用获取文本值,另一个设置ItemsSource
:
Thread test = new Thread(() =>
{
String text, password, ipText, domainText;
// !!!!!!This one should be simple Invoke because otherwise variables may not get their
// values before calls. Thanks @ScottChamberlain.!!!!!!
datagrid_Disks.Dispatcher.Invoke(
new Action(() =>
{
text = textbox_Username.Text;
password = textbox_password.Password;
ipText = textbox_IP.Text,
domainText = textbox_Domain.Text
}));
var result = Server.GetDisksInfo(text,
password,
ipText,
domainText);
datagrid_Disks.Dispatcher.BeginInvoke(
new Action(() =>
{
datagrid_Disks.ItemsSource = result;
}));
});
test.Start();
或(感谢@RohitVals)
您可以在运行线程之前获取这些值,以避免双重调度:
text = textbox_Username.Text;
// ...
Thread test = ...
或者
您可能需要尝试MVVM模式-http: //msdn.microsoft.com/zh-cn/magazine/dd419663.aspx。刚开始时,它看上去似乎很吓人,太复杂了,几乎没有优势,但是随着时间的推移,您会发现它的优点。
这篇特别的文章涉及MVVM和Dispathcer- http://msdn.microsoft.com/zh-cn/magazine/dn630646.aspx
PS:如果您的GetDisksInfo
方法使用延迟执行(如LINQ),则应在使用前枚举结果:
var result = Server.GetDisksInfo(text,
password,
ipText,
domainText).ToArray();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句