我有一个BackgroundWorker一个WinForm:的BackgroundWorker:出现InvalidOperationException在RunWorkerCompleted
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SeoTools.Utils;
namespace SeoTools.UI
{
public partial class UIProgress : Form
{
public UIProgress(DoWorkEventHandler doWorkEventHandler, RunWorkerCompletedEventHandler runWorkerCompletedEventHandler)
{
InitializeComponent();
this.backgroundWorker.WorkerReportsProgress = true;
this.backgroundWorker.WorkerSupportsCancellation = true;
this.backgroundWorker.DoWork += doWorkEventHandler;
this.backgroundWorker.RunWorkerCompleted += runWorkerCompletedEventHandler;
}
public void Start()
{
var foo = SynchronizationContext.Current;
backgroundWorker.RunWorkerAsync();
}
private void btnStop_Click(object sender, EventArgs e)
{
btnStop.Enabled = false;
btnStop.Text = "Stopping...";
backgroundWorker.CancelAsync();
}
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
try
{
wdgProgressBar.Value = e.ProgressPercentage;
if (this.Visible == false)
{
this.ShowDialog();
this.Update();
}
}
catch (InvalidOperationException) {}
}
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.Hide(); //Here I get a InvalidOperationException
this.Dispose();
}
}
}
我第一次运行这个它工作正常。但拨打this.Hide()
时第二次获得InvalidOperationException
。
“附加信息:跨线程操作无效:控制'UIProgress'从其创建的线程以外的线程访问。”
奇怪的是在开始第一次运行foo()从一个WindowsFormsSyncronizationContext,但在第二次尝试这是一个System.Threading.SyncronizationContext。
我正在写的应用程序是一个ExcelDna插件。
编辑
start()被称为是这样的:
UIProgress uiProgress = new UIProgress(
delegate(object sender, DoWorkEventArgs args)
{
....
},
delegate(object sender, RunWorkerCompletedEventArgs args)
{
...
}
);
uiProgress.Start();
如何调用'Start'? – kennyzx 2014-12-07 15:23:00
@kennyzx我已更新我的问题 – 2014-12-07 17:21:24
我在SyncronizationContext上发现了一个旧的[post](http://blogs.msdn.com/b/mattdotson/archive/2006/02/13/531315.aspx),该技术,你可以保存'WindowsFormsSyncronizationContext'供以后使用。不知道如何切换到另一个'SyncronizationContext',也许是Excel-DNA环境...需要一些艰苦的调试时间。 – kennyzx 2014-12-08 13:41:25