我是 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();
}
}
最佳答案
如果您使用的是 .NET 4.0,您可能需要考虑使用 Task来自 Task parallel library 的类(class).阅读它,因为你说你是线程的新手。使用起来更加灵活。
此外,我认为此链接可能对您很有帮助:
关于c# - 正确的线程方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8671277/