Timing issue - DGV refreshes before process amends the data

前端 未结 3 748
孤城傲影
孤城傲影 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:41

    You can call WaitForExit on the return value of Process.Start.

    0 讨论(0)
  • 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";
    }
    
    0 讨论(0)
  • 2021-01-24 06:03

    You can call p.WaitForExit() on the process, but don't do that on the main thread (ie in a buttonClick);

    You'll want something like:

    //untested
    private void btRunProcessAndRefresh_Click(object sender, EventArgs e)
    { 
        var p = Process.Start(@"\\fileserve\department$\ReportScheduler_v3.exe", "12"); 
        p.Exited += ProcessExited;
        p.EnableRaisingEvents = true;
        //InitializeGridView(); 
    }     
    
    void ProcessExited(object sender, EventArgs e)
    {
        InitializeGridView();    
    }
    
    0 讨论(0)
提交回复
热议问题