我在表单上有一个按钮,用于启动一个进程,在 x(不同)秒后,更改数据库表 Y 中的一些数据。调用 InitializeGridView() 然后刷新显示前面提到的表 Y 的 DGV。问题是InitializeGridView() 在进程之前完成,因此进程所做的更改不会反映出来。如何让 InitializeGridView 等待该过程完成?
private void btRunProcessAndRefresh_Click(object sender, EventArgs e){
Process.Start(@"\\fileserve\department$\ReportScheduler_v3.exe", "12");
InitializeGridView();
}
EDIT
我最终得到以下结果。现在的问题是,如果该过程需要 10 分钟,那么应用程序将冻结 10 分钟。我想我需要学习如何多线程!
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()
there.
- 让线程调用您的
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";
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)