【发布时间】:2012-01-30 01:45:21
【问题描述】:
我对 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 线程的含义后,再做一些研究。
标签: c# .net wpf multithreading optimization