c# - WPF 中线程的一个非常基本的解释?

标签 c# .net wpf multithreading

我对 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/

相关文章:

c# - 无法从均受 Azure AD B2C 保护的 MVC Web 应用程序访问 WebApi

c# - MVC : POST controller method get empty Dictionary

c# - WP7 同步网页请求

c# - 将环境数据添加到线程

c# - AffectsMeasure 或 AffectsArrange

c# - 如何从 Visual Studio Team Services 运行 ASP.NET Core Entity Framework 迁移

c# - 读取 Json 文件时不支持给定路径的格式

c# - 为什么 if 条件不检查空值

wpf - 如何在 XAML 中根据窗口或屏幕大小设置网格列最大宽度

wpf - 如果是基于WPF的Visual Studio 2010,为什么我不能用反射器打开它?