正如其他人所说的那样,使用这种BackgroundWorker
或其他方法同时进行工作.
你可以在你的下面声明它Window
,在Loaded
事件的某个地方初始化它,并在Click
事件中使用它.这是你的方法,修改后使用BackgroundWorker
,假设你已经在Window
as 下声明了它_bw
:
private void Window_Loaded(object sender, RoutedEventArgs e) { _bw = new BackgroundWorker(); _bw.DoWork += new DoWorkEventHandler((o, args) => { //Long stuff here this.Dispatcher.Invoke((Action)(() => txtLog.AppendText(Environment.NewLine + "Blabla"))); }); _bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler((o, args) => { //End long stuff here this.Dispatcher.Invoke((Action)(() => this.button1.IsEnabled = true)); }); } private void button1_Click(object sender, RoutedEventArgs e) { this.button1.IsEnabled = false; _bw.RunWorkerAsync(); }
请注意,从另一个线程修改UI的任何内容都必须在一个Dispatcher.Invoke
或Dispatcher.BeginInvoke
调用中完成,WPF不允许您DependencyProperty
从任何线程获取或设置值,而是创建对象的那个(更多关于此处).
如果你想读取txtLog
而不是修改它,代码将是相同的:
//Long stuff here this.Dispatcher.Invoke((Action)(() => { string myLogText = txtLog.Text; myLogText = myLogText + Environment.NewLine + "Blabla"; txtLog.Text = myLogText; }));