我有一個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