如何将例程拆分为线程?

时间:2012-03-15 09:57:28

标签: c# winforms multithreading

  

可能重复:
  Timing issue - DGV refreshes before process amends the data

我有以下代码

private void btRunReport_Click(object sender, EventArgs e){ 

    Process p = new Process(); 
    p.StartInfo.FileName = @"\\fileserve\department$\ReportScheduler_v3.exe"; 
    p.StartInfo.Arguments = "12"; 
    p.Start(); 
    p.WaitForExit(); 
    InitializeGridView(); 
} 

p将更新数据库表X. InitializeGridView更新反映表X的DGV。

问题是如果p需要10分钟才能运行,那么winForm会在它到达InitializeGridView()之前被冻结。我需要帮助的是如何使表单在​​一个单独的线程中启动进程,该线程在幕后工作并运行InitializeGridView()?

1 个答案:

答案 0 :(得分:1)

如果您需要在流程完成后运行InitialilzeGridView()方法:

  1. Dispatcher.CurrentDispatcher作为_currentDispatcher。
  2. 在一个单独的主题中启动进程并将其WaitForExit()放在那里。
  3. 让线程通过InitializeGridview()
  4. 调用您的_currentDispatcher.BeginInvoke方法

    这里有一些代码可以帮助您:

    注意:您需要通过项目的“添加引用”对话框添加对WindowsBase的引用。

    using System;
    using System.Diagnostics;
    using System.Threading;
    using System.Windows.Forms;
    using System.Windows.Threading;
    
    private readonly Dispatcher _currentDispatcher = Dispatcher.CurrentDispatcher;
    private delegate void ReportingSchedulerFinishedDelegate();
    
    private void btRunReport_Click(object sender, EventArgs e)
    {
        btRunReport.Enabled = false;
        btRunReport.Text = "Processing..";
        var thread = new Thread(RunReportScheduler);
        thread.Start();
    }
    
    private void InitializeGridView()
    {
        // Whatever you need to do here
    }
    
    private void RunReportScheduler()
    {
        Process p = new Process();
        p.StartInfo.FileName = @"\\fileserve\department$\ReportScheduler_v3.exe";
        p.StartInfo.Arguments = "12";
        p.Start();
        p.WaitForExit();
        _currentDispatcher.BeginInvoke(new ReportingSchedulerFinishedDelegate(ReportingSchedulerFinished), DispatcherPriority.Normal);
    }
    
    private void ReportingSchedulerFinished()
    {
        InitializeGridView();
        btRunReport.Enabled = true;
        btRunReport.Text = "Start";
    }