我对 WPF 非常陌生。我在 Internet 上查找了几个有关线程的示例和教程。他们有自己的描述方式。但是对于像我这样的天真,我想用我自己的方式来理解。
而且我可以使用数据库更新功能开始我的第一个线程。
场景如下:
我有大量数据要插入数据库。现在让我们假设以下代码(这个过程将在我点击“继续”按钮后立即启动:
int initial = 0;
int maxData = 10
while (initial<maxData) {
//Database query here
}
上述过程将在不同的线程中运行。
接下来我在主窗口中有一个“标签”。对于每个数据库查询,我想在标签中显示一些消息。
例如,
// this will happen in default UI thread.
label.Content = "Updating"; // Specifically for @TomTom ;)
编辑: 我做了以下事情:
var task = new Task(() =>
{
for (int i=0; i<10; i++) {
//Create new Grid HERE
// Add Table with some dynamic data here..
// print the above Grid here.
}
});
task.ContinueWith((previousTask) =>
{
label.Content = printerStatus(); // will return "Out of Paper", "printing", "Paper jam", etc.
},
TaskScheduler.FromCurrentSynchronizationContext());
label.Content = "Sending to printer";
程序将返回错误“调用线程必须是 STA,因为许多 UI 组件都需要这个。”
我不知道下一步该做什么。请帮忙!
最佳答案
您需要为长时间运行的任务使用 BackgroundWorker,并使用 Dispatcher 更新其间的 UI
//create background worker
BackgroundWorker worker = new BackgroundWorker();
//assign it work
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
//start work
worker.RunWorkerAsync();
//this work will be done in background
void worker_DoWork(object sender, DoWorkEventArgs e)
{
SET initial = 0;
SET maxData = 1000
DO UNTIL initial <1000
CREATE db query "INSERT INTO (col1,col2,col3) VALUES(value1,value2,value3);"
//in between your work do this to update label
label.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,new Action(delegate()
{
Label.Content = "SomeValue";
}
));
END DO
}
关于c# - WPF 中线程的一个非常基本的解释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8665158/