Timing issue - DGV refreshes before process amends the data

前端 未结 3 751
孤城傲影
孤城傲影 2021-01-24 05:05

I\'ve got a button on a form that starts a process which, after x (varies) seconds, changes some data in a database table Y. The call InitializeGridView() then refreshes the DGV

3条回答
  •  盖世英雄少女心
    2021-01-24 05:56

    A follow-up question was closed so here's a copy of my answer:

    If you need your InitialilzeGridView() Method to run after the process has finished:

    1. Make available Dispatcher.CurrentDispatcher as _currentDispatcher.
    2. Start the Process in a seperate Thread and have it WaitForExit() there.
    3. Have the Thread call your InitializeGridview() Method via _currentDispatcher.BeginInvoke.

    Here's some code to get you going:

    Note: You will need to add a Reference to WindowsBase via the Add Reference dialog of your project.

    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";
    }
    

提交回复
热议问题