我对WPF很新颖。刚开始学习线程。线程的正确方法
这是我的场景: 我用一个名为START的按钮创建了一个程序。当单击开始按钮时,它开始在不同的线程中执行一些复杂的任务。在开始复杂任务之前,它还在另一个STA线程(技术上我不知道我在说什么)创建了中的UI元素。
这里是一个示例代码:
// 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();
}
}
如果你真正理解你在说什么,可能会有所帮助。当你了解STA线程的含义时,做一些研究回来。 – 2011-12-29 18:40:41