我正在使用BackgroundWorker进行一些活动,例如:
BackgroundWorker worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.WorkerSupportsCancellation = true;
worker.DoWork += new DoWorkEventHandler(Worker_DoWork);
worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
worker.RunWorkerAsync();
在DoWork内部,我有:
void Worker_DoWork(object sender, DoWorkEventArgs e)
{
int totalExecucao = 2;
int count = 0;
setMensagemText(count++, "Verificando Banco de dados...", totalExecucao);
VerificaDataBase();
setMensagemText(count++, "Verificando Configurações Locais", totalExecucao);
verificaConfiguracaoLocal();
worker.ReportProgress(100);
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
{
MainWindow mw = new MainWindow();
mw.Show();
this.Close();
}));
我必须检查“configuraçõeslocais”,如果没有注册,则必须打开一个页面,并且用户需要进行一些配置并保存,然后结束打开MainView Form,以检查是否使用此代码: / p>
private void verificaConfiguracaoLocal()
{
LocalBean localBean = new LocalBean();
localBean.CarregaModel();
if (localBean.Model.Id > -1)
//if(localBean.Model.Id == 0)
{
Thread novaNotificacao = new Thread(new ThreadStart(Notify));
novaNotificacao.SetApartmentState(ApartmentState.STA);
novaNotificacao.Start();
worker.CancelAsync();
void Notify()
{
LocalPage lp = new LocalPage();
Window win2 = new Window();
win2.Content = lp;
win2.Show();
}
}
}
发生了什么 在处理过程中,页面是自动打开和关闭的,按顺序他将进行下一个检查,在这种情况下将打开MainWindow。
我必须: 打开表单时,我需要BackgroundWorker等待用户关闭Win2,然后继续进行检查
编辑============================================== ========================
我尝试过:
private AutoResetEvent _workerCompleted = new AutoResetEvent(false);
setMensagemText(count++, "Verificando Banco de dados...", totalExecucao);
VerificaDataBase();
_workerCompleted.WaitOne();
setMensagemText(count++, "Verificando Configurações Locais", totalExecucao);
verificaConfiguracaoLocal();
_workerCompleted.WaitOne();
private void verificaConfiguracaoLocal()
{
LocalBean localBean = new LocalBean();
localBean.CarregaModel();
verificaAbrirPage(localBean.Model.Id, typeof(LocalPage));
if (LocalBean.ModelStatic.Id.Equals(0))
{
NotificacaoUtil.Error("Para o sistema carregar corretamente, é necessário ter uma configuração local. O sistema será finalizado!");
Environment.Exit(0);
}
}
private void verificaAbrirPage(long id, Type page)
{
if (id.Equals(0))
{
Dispatcher.BeginInvoke(new Action(() =>
{
Page lp = (Page)Activator.CreateInstance(page);
Window win2 = new Window();
win2.Content = lp;
win2.Closed += (s, a) =>
{
_workerCompleted.Set();
};
win2.Show();
}));
}
else
{
_workerCompleted.Set();
}
}
但不起作用