正确的穿线方法
本文关键字:方法 | 更新日期: 2023-09-27 18:19:13
我对WPF很陌生。然后开始学习穿线。
这是我的方案:我创建了一个带有START按钮的程序。当开始按钮被点击,它开始做一些复杂的任务在不同的线程。就在开始复杂的任务之前,它还创建了一个UI元素在另一个STA线程(技术上我不知道我在说什么)。
下面是一个示例代码:// button click event
private void button1_Click(object sender, RoutedEventArgs e)
{
System.Threading.Thread myThread = new System.Threading.Thread(
() => buttonUpdate("Hello "));
myThread.Start();
}
private void buttonUpdate(string text)
{
System.Threading.Thread myThread = new System.Threading.Thread(createUI);
myThread.SetApartmentState(System.Threading.ApartmentState.STA);
// set the current thread to background so that it's existant will totally
// depend upon existance of main thread.
myThread.IsBackground = true;
myThread.Start();
// Please don't read this loop it's just for my entertainment!
for (int i = 0; i < 1000; i++)
{
System.Threading.Thread.Sleep(100);
button1.updateControl(new Action(
() => button1.Content = text + i.ToString()));
if (i == 100)
break;
}
// close main window after the value of "i" reaches 100;
this.updateControl(new Action(()=>this.Close()));
}
// method to create UI in STA thread. This thread will be set to run
// as background thread.
private void createUI()
{
// Create Grids and other UI component here
}
上面的代码成功地完成了我想做的事情。但你认为这是正确的方法吗?到目前为止,我还没有遇到任何问题。
编辑:哎呀,我忘了提到这个类:
public static class ControlException
{
public static void updateControl(this Control control, Action code)
{
if (!control.Dispatcher.CheckAccess())
control.Dispatcher.BeginInvoke(code);
else
code.Invoke();
}
}
如果你使用的是。net 4.0,你可能会考虑使用Task并行库中的Task类。既然你说你是线程的新手,就读一读吧。使用起来更灵活。
我也认为这个链接可能对你很有帮助:
http://www.albahari.com/threading/似乎没有很好的理由使用两个线程。
应该能够在主线程上执行createUI()
。当需要填充这些控件时,这就足够复杂了。
只有一个线程可以与UI交互。如果要向页面或窗口添加控件,则必须使用创建该页面或窗口的线程。典型的场景是使用线程在后台创建昂贵的数据或对象,然后在回调(在主线程上运行)中检索结果并将适当的数据绑定到UI。看看使用BackgroundWorker,因为它会为你处理很多线程细节。http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx为什么要在另一个头上创建UI对象?