可能重复:
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()?
答案 0 :(得分:1)
如果您需要在流程完成后运行InitialilzeGridView()方法:
Dispatcher.CurrentDispatcher
作为_currentDispatcher。WaitForExit()
放在那里。InitializeGridview()
。_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";
}