一个非常基本的解释线程在WPF?线程、基本、WPF

2023-09-06 18:40:23 作者:浪味小仙女吖

我非常非常新的WPF。我看着在互联网上的几个例子和有关线程教程。他们已经用自己的方式来描述。但是,对于天真像我这样的,我想了解我自己的风格。

I am very very new to WPF. I looked in the internet for several examples and tutorials about threading. They've their own way to describe. But for naive like me, I want to understand with my own style.

和我可以开始我的第一次过使用超线程数据库更新功能。

And I can begin my ever first Threading using database update feature.

下面是该方案:

我有大量的数据在数据库中插入。现在让我们假设以下code(这个过程会,只要我打发起继续按钮:

I have a large amount of data to insert in the database. For now let's assume the following code (this process will initiate as soon as I hit "proceed" button:

int initial = 0;
int maxData = 10
while (initial<maxData) {
   //Database query here
}

以上过程将在不同的线程中运行。

The above process will run in different thread.

接下来,我在我的主窗口中的标签​​。对于每个数据库查询,我想显示在标签的一些消息。

Next I have a "label" in my main window. For each database query, I would like to show some message in label.

例如,

// this will happen in default UI thread.
label.Content = "Updating"; // Specifically for @TomTom ;)

编辑: 我已经做了以下内容:

I've done the following:

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组件都需要这个。

The program will return error saying "The calling thread must be STA, because many UI components require this."

我不知道下一步该怎么做。请帮帮忙!

I have no idea what to do next. Please help!

推荐答案

您需要使用的BackgroundWorker你的长期运行的任务,并使用分派器

You need to use the BackgroundWorker for your long running task and use Dispatcher to update UI in between

 //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
  }