BackgroundWorker无法在VSTO中工作 [英] BackgroundWorker Not working in VSTO

查看:78
本文介绍了BackgroundWorker无法在VSTO中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一名背景工作者.在调用工作程序之前,我先禁用按钮并使gif可见.然后,我调用runworkerasync方法,该方法可以正常运行直到完成.在"RunWorkerCompleted()"上,我遇到了跨线程错误.知道为什么吗?

I have a background worker. Before I invoke the worker I disable a button and make a gif visible. I then invoke the runworkerasync method and it runs fine until comleteion. On the 'RunWorkerCompleted()' I get a cross thread error. Any idea why?

    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似乎是一个问题.

It seems to be an issue with VSTO and BackgroundWorker.

解决方案位于此处

基本上你需要打电话

System.Threading.SynchronizationContext.SetSynchronizationContext(new WindowsFormsSynchronizationContext());

在致电RunWorkerAsync之前.效果很好.

before you call RunWorkerAsync. Works great.

为避免每次在AddIn的主类中可能有一个静态成员并重新使用它时都实例化该对象.这样,您只需实例化一次.

To avoid instantiating the object every time you may have a static member in you AddIn's main class and reuse it. This way you only instantiate once.

这篇关于BackgroundWorker无法在VSTO中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆