本文介绍了如何运行两个操作同时在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在WPF应用程序有问题。我有一个自定义的 CircularProgressBar
。当我从数据库中检索它需要几秒钟的数据。
I have a problem in my WPF app. I have a custom CircularProgressBar
. When I retrieve data from database it takes a few seconds.
我想显示 CircularProgressBar
我的应用程序虽然该数据被检索
I would like to show the CircularProgressBar
in my app while the data is retrieved.
这代码运行在 CircularProgressBar
:
CircularProgressBar cb = new CircularProgressBar();
stk.Children.Add(cb);
ThreadStart thStart = delegate()
{
ThreadStart inv = delegate()
{
stk.Children.Remove(cb);
};
this.Dispatcher.Invoke(inv, null);
};
Thread myThread = new Thread(thStart);
myThread.Start();
在我的自定义类(打印机
)。
in my custom class (Printer
).
和在哪里我把这个窗口:
And where I call this window:
Printer p = new Printer();
p.Show();
//Code For retrieve Data from DataBase
p.close();
所以发生这种情况: CircularProgressBar
显示了几秒钟,它没有运行。哪里是我的错误。
So this happens : CircularProgressBar
shows for a few seconds and it not running. Where is my bug?
推荐答案
您可以简单地使用背景工人:
You can simply use background worker:
private BackgroundWorker bw = new BackgroundWorker();
bw.WorkerReportsProgress = true;
bw.WorkerSupportsCancellation = true;
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
//load data from database
System.Threading.Thread.Sleep(1);
worker.ReportProgress(progressbar_value);
}
private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
Progress.value= progressbar_value;
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//progress completed
}
这篇关于如何运行两个操作同时在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!