时序问题 – DGV在进程修改数据之前刷新
我在表单上有一个按钮,启动一个进程,在x(变化)秒后,更改数据库表Y中的一些数据。调用InitializeGridView()然后刷新显示前面提到的表Y的DGV。问题是那样的InitializeGridView()在进程之前完成,因此不会反映进程所做的更改。 如何让InitializeGridView等待进程完成?
private void btRunProcessAndRefresh_Click(object sender, EventArgs e){ Process.Start(@"\\fileserve\department$\ReportScheduler_v3.exe", "12"); InitializeGridView(); }
编辑
我最终得到了以下内容。 现在的问题是,如果该过程需要10分钟,那么应用程序将被冻结10分钟。 我想我需要学习如何multithreading!
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(); }
后续问题已经结束,所以这里是我答案的副本:
如果您需要在进程完成后运行InitialilzeGridView()方法:
- 将
Dispatcher.CurrentDispatcher
作为_currentDispatcher提供。 - 在一个单独的线程中启动进程并在那里使用
WaitForExit()
。 - 让Thread通过
_currentDispatcher.BeginInvoke
调用您的InitializeGridview()
方法。
这里有一些代码可以帮助您:
注意:您需要通过项目的“添加引用”对话框添加对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"; }
你可以在进程上调用p.WaitForExit(),但不要在主线程上执行(即在buttonClick中);
你会想要这样的东西:
//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(); }
您可以在Process.Start的返回值上调用WaitForExit。