小编Ale*_*der的帖子

包含线程的类的IDisposable实现

早上好!我们假设我们有以下类:

class MultithreadOperation : IDisposable
{
    private IList<Thread> operationThreads;

    public void StartOperation()
    {
          // Initialize and start threads and put them to operationThreads
    }

    public void StopOperation()
    {
          // Aborts each thread.
    }

    public void Dispose()
    {
          Dispose(true);
          GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
         if (!disposed)
         {
              disposed = true;
              if (disposing)
              {
                    // Release managed resources.
                    #1:
                    StopOperation();
              }
              // Release unmanaged resources.
              #2:
              StopOperation();
         }
    }

    ~MultithreadOperation()
    {
         Dispose(false);
    }
}
Run Code Online (Sandbox Code Playgroud)

实际上,如果实例被丢弃,我需要停止所有线程.此外,如果实例被垃圾收集,我需要停止所有线程(否则,线程将仍然存活,这对我不利).当然,在#1中调用StopOperation()方法是完全合法的.

我想知道如果我们调用StopOperation()到位#2,是否有任何陷阱?据我所知,当~MultithreadOperation()执行时,线程列表可能已被垃圾收集.此外,我已经看到很多建议,以避免任何代码引用Finalize实现中的托管资源,尤其是实例字段.

此外,听到有关此问题的不同方法会很有趣.谢谢!

.net c# multithreading

5
推荐指数
1
解决办法
1174
查看次数

标签 统计

.net ×1

c# ×1

multithreading ×1