从其他类访问Windows窗体控件的跨线程问题

时间:2013-06-06 21:46:14

标签: multithreading winforms ssis

我正在从Windows窗体执行SSIS包。在按钮单击表单时,我正在执行SSIS包并实例化通过“this”的PackageEventListener,即Form1。

var app = new SSISApplication();
_pkg = app.LoadPackage(pkgLocation, null);
var listener = new PackageEventListener(this);
DTSExecResult pkgResults = _pkg.Execute(null, null, listener, null, null);

我也在重写DefaultEvents以从PackageEventListener.cs类中的包中获取进度。在构造函数中,我得到Form1并使用它来获取设置lblExportStatus标签的public方法。

public class PackageEventListener : DefaultEvents
{
     private Form1 formInstance;
     public PackageEventListener(Form1 form)
     {
        formInstance = form;
     }

     public override void OnProgress(TaskHost taskHost, string progressDescription, int percentComplete, int progressCountLow,int progressCountHigh, string subComponent, ref bool fireAgain)
     {
          var message = string.Format("{0}:{1}", percentComplete, progressDescription);   
          formInstance.SetMsg(message);
          base.OnProgress(taskHost, progressDescription, percentComplete, progressCountLow, progressCountHigh, subComponent, ref fireAgain);
     }
}

我想使用OnProgress方法中的消息更新Windows窗体中的标签。

我在windows窗体中创建了一个公共方法来设置标签,如下所示:

public void SetMsg(string msg)
{
   if (lblExportStatus.InvokeRequired)
       lblExportStatus.Invoke(new System.Action(() => lblExportStatus.Text = msg));
   else
       lblExportStatus.Text = msg;
}

我收到此错误:线程''(0x3930)已退出,代码为0(0x0)。

永远不会在SetMsg方法中为lblExportStatus赋值。 InvokeRequired始终为true。并抛出异常“发生异常'Microsoft.VisualStudio.Debugger.Runtime.CrossThreadMessagingException'。”

请帮助解决此问题。提前谢谢!!

0 个答案:

没有答案