【问题标题】:Do not call Dispose of parts in dispose MEF不要在 dispose MEF 中调用 Dispose of parts
【发布时间】:2012-03-23 14:51:04
【问题描述】:

我在应用程序结束时遇到了一个问题,容器没有调用部件的 Dispose 方法。 基于MEF的应用。

当我显式调用Dispose容器时,在parts上调用了matod Dispose,但是如果你只是关闭程序,不会调用parts的Dispose,为什么? 如何确定关闭程序时是由容器MEF的所有部分的Dispose方法引起的?

[Export(typeof(IMyClass))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class MyClass: IDisposable, IMyClass
{
    private bool disposed = false;

    public void Dispose()
    {
        Dispose(true);

        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if(!this.disposed)
        {
            if(disposing)
            {
                // Dispose managed resources.

            }

            disposed = true;
        }
    }

    ~MyClass()
    {
        Dispose(false);
    }
}

【问题讨论】:

  • 您的“部件”不需要在程序退出时处理。
  • 比如段子里有一个线程,不是后台,而这个线程应该是正确的停止方式,你要怎么做呢?

标签: c# containers mef dispose


【解决方案1】:

当我显式调用Dispose容器时,对parts调用了matod Dispose,但是如果只是关闭程序,不会调用parts的Dispose,为什么?

因为使用完容器后必须将其丢弃。如果您的程序在退出之前没有调用 CompositionContainer.Dispose(),那么这是您的程序中的一个错误。

【讨论】:

    【解决方案2】:

    Wim Coenen,谢谢,我认为MEF的破坏必须在零件上调用Destruct。 我确保按照我需要的方式工作:

    public partial class MyBootstrapper : MefBootstrapper
    {
       public MyBootstrapper()
       {
          App.Current.Exit += new ExitEventHandler(Current_Exit);
       }
    
       void Current_Exit(object sender, ExitEventArgs e)
       {
          if (this.Container != null)
             this.Container.Dispose();
       }
    ...
    

    【讨论】:

      猜你喜欢
      • 2013-01-09
      • 1970-01-01
      • 2010-12-07
      • 2016-06-25
      • 2012-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-26
      相关资源
      最近更新 更多