我有一名背景 worker 。在调用工作程序之前,请先禁用按钮并使gif可见。然后,我调用runworkerasync方法,该方法可以正常运行直至完成。在“RunWorkerCompleted()”上,我收到一个跨线程错误。知道为什么吗?
private void buttonRun_Click(object sender, EventArgs e)
{
if (comboBoxFiscalYear.SelectedIndex != -1 && !string.IsNullOrEmpty(textBoxFolderLoc.Text))
{
try
{
u = new UpdateDispositionReports(
Convert.ToInt32(comboBoxFiscalYear.SelectedItem.ToString())
, textBoxFolderLoc.Text
, Properties.Settings.Default.TemplatePath
, Properties.Settings.Default.ConnStr);
this.buttonRun.Enabled = false;
this.pictureBox1.Visible = true;
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
bw.RunWorkerAsync();
//backgroundWorker1.RunWorkerAsync();
}
catch (Exception ex)
{
MessageBox.Show("Unable to process.\nError:" + ex.Message, Properties.Settings.Default.AppName);
}
}
}
void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
buttonRun.Enabled = true;
pictureBox1.Visible = false;
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
u.Execute();
}
最佳答案
VSTO和BackgroundWorker似乎是一个问题。
解决方案是here。
基本上你需要打电话
System.Threading.SynchronizationContext.SetSynchronizationContext(new WindowsFormsSynchronizationContext());
在您致电
RunWorkerAsync
之前。效果很好。为了避免每次在AddIn的主类中都有一个静态成员并实例化该对象时,都要实例化该对象。这样,您只需实例化一次。
关于c# - BackgroundWorker无法在VSTO中工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2449515/