我正在尝试在UI中进行更改,然后让我的函数运行 这是我的代码:
private void btnAddChange_Document(object sender, RoutedEventArgs e)
{
System.Threading.ThreadStart start = delegate()
{
// ...
// This will throw an exception
// (it's on the wrong thread)
Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(changest));
//this.BusyIndicator_CompSelect.IsBusy = true;
//this.MainWindow_parent.BusyIndicator_MainWindow.IsBusy = true;
};
// Create the thread and kick it started!
new System.Threading.Thread(start).Start();
}
public void changest()
{
this.BusyIndicator_CompSelect.IsBusy = true;
this.MainWindow_parent.BusyIndicator_MainWindow.IsBusy = true;
t = "Creating document 1/2..";
}
我想在ui更新后/在ThreadStart'start'结束后运行的函数:
string x = "";
for(int i =0;i<=1000;i++)
{
x+= i.ToString();
}
MessageBox.Show(x);
那我该怎么办? 提前致谢, 嚣。
答案 0 :(得分:2)
我假设你想要异步执行一些动作。对?为此,我建议在WPF中使用BackgroundWorker - 类:
BackgroundWorker bgWorker = new BackgroundWorker() { WorkerReportsProgress=true};
bgWorker.DoWork += (s, e) => {
// Do here your work
// Use bgWorker.ReportProgress(); to report the current progress
};
bgWorker.ProgressChanged+=(s,e)=>{
// Here you will be informed about progress and here it is save to change/show progress.
// You can access from here savely a ProgressBars or another control.
};
bgWorker.RunWorkerCompleted += (s, e) => {
// Here you will be informed if the job is done.
// Use this event to unlock your gui
};
// Lock here your GUI
bgWorker.RunWorkerAsync();
我希望,这就是你的问题所在。
答案 1 :(得分:1)
对你想要完成的事情略有困惑,但我相信这就是你所追求的......
private void btnAddChange_Document(object sender, RoutedEventArgs e)
{
System.Threading.ThreadStart start = delegate()
{
//do intensive work; on background thread
string x = "";
for (int i = 0; i <= 1000; i++)
{
x += i.ToString();
}
//done doing work, send result to the UI thread
Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
new Action<int>(changest));
};
//perform UI work before we start the new thread
this.BusyIndicator_CompSelect.IsBusy = true;
this.MainWindow_parent.BusyIndicator_MainWindow.IsBusy = true;
t = "Creating document 1/2..";
//create new thread, start it
new System.Threading.Thread(start).Start();
}
public void changest(int x)
{
//show the result on the UI thread
MessageBox.Show(x.ToString());
}