在对象完成时取消任务

时间:2016-04-06 09:48:41

标签: c# task-parallel-library task idisposable finalizer

我有一个类,它启动一个Task,并希望确保在对象被垃圾回收时Task停止。

我已经实现了IDisposable模式,以确保如果对象是手动处理或在使用块中使用,则Task会正确停止。 然而,我无法保证最终用户将调用Dispose()或使用using块中的对象。我知道垃圾收集器最终会调用Finalizer - 这是否意味着任务仍在运行?

public class MyClass : IDisposable
{
    private readonly CancellationTokenSource feedCancellationTokenSource = 
          new CancellationTokenSource();

    private readonly Task feedTask;

    public MyClass()
    {
        feedTask = Task.Factory.StartNew(() =>
        {
            while (!feedCancellationTokenSource.IsCancellationRequested)
            {
                // do finite work
            }
        });
    }

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

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            feedCancellationTokenSource.Cancel();
            feedTask.Wait();

            feedCancellationTokenSource.Dispose();
            feedTask.Dispose();
        }
    }

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

this question中建议添加一个从终结器设置并从任务中观察到的挥发性bool。这是推荐的,还是有更好的方法来实现我的需求?

(我使用.NET 4因此使用TaskFactory.StartNew而不是Task.Run)

修改

为问题提供一些上下文 - 实际上并未在上面的代码片段中显示:我正在创建一个网络客户端类,它具有通过定期向服务器发送数据包来保持活动的机制。我选择不将所有这些细节放在示例中,因为它与我的具体问题无关。但是,我真正想要的是用户能够将KeepAlive布尔属性设置为true,这将启动一个任务,每60秒将数据发送到服务器。如果用户将该属性设置为false,则该任务将停止。 IDisposable让我90%的方式,但它依赖于用户正确处理它(明确地或通过使用)。我不想向用户公开保持活动的任务,以便他们明确取消,我只想要一个简单的" KeepAlive = true / false来启动/停止任务我希望任务在用户完成对象时停止 - 即使他们没有正确处理它。我开始认为这是不可能的!

2 个答案:

答案 0 :(得分:2)

我将草拟一个答案。我不是百分之百地相信这会奏效。最终确定是一个复杂的问题,我并不精通它。

  1. 任务中没有任何对象引用,无论什么对象应该最终确定。
  2. 您无法触摸终结器中其他未知安全的物体。内置的.NET类通常不会记录此安全属性。你不能(通常)依赖它。
  3. class CancellationFlag { public volatile bool IsSet; }
    

    您现在可以在任务和MyClass之间共享此类的实例。任务必须轮询标记,MyClass必须设置它。

    为了确保任务不会意外地引用外部对象,我将构造如下代码:

    Task.Factory.StartNew(TaskProc, state); //no lambda
    
    static void TaskProc(object state) { //static
    }
    

    通过这种方式,您可以通过state显式线程化任何状态。这至少应该是CancellationFlag的一个实例,但在任何情况下都不能引用MyClass

答案 1 :(得分:1)

我创建了以下程序以探索差异......

根据我对它的观察,看起来它是一个取消令牌还是一个易变的bool没什么区别,真正重要的是没有使用lambda表达式调用Task.StartNew方法。

编辑以澄清:如果lambda引用静态方法,它实际上很好:当lambda导致包含对包含类的引用时出现问题:so要么引用父类的成员变量,要么引用父类的实例方法。

如果你得出同样的结论,请试一试,告诉我。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication7
{
    class Program
    {
        static void Main(string[] args)
        {
            Logger.LogFile = @"c:\temp\test\log.txt";

            Task.Run(() =>
            {
                // two instances (not disposed properly)

                // if left to run, this background task keeps running until the application exits
                var c1 = new MyClassWithVolatileBoolCancellationFlag();

                // if left to run, this background task cancels correctly
                var c2 = new MyClassWithCancellationSourceAndNoLambda();

                //
                var c3 = new MyClassWithCancellationSourceAndUsingTaskDotRun();

                //
                var c4 = new MyClassWithCancellationSourceAndUsingTaskDotRunButNoParentReference();


            }).GetAwaiter().GetResult();

            // instances no longer referenced at this point

            Logger.Log("Press Enter to exit");
            Console.ReadLine(); // press enter to allow the console app to exit normally: finalizer gets called on both instances
        }


        static class Logger
        {
            private static object LogLock = new object();
            public static string LogFile;
            public static void Log(string toLog)
            {
                try
                {
                    lock (LogLock)
                        using (var f = File.AppendText(LogFile))
                            f.WriteLine(toLog);

                    Console.WriteLine(toLog);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Logging Exception: " + ex.ToString());
                }
            }

        }

        // finalizer gets called eventually  (unless parent process is terminated)
        public class MyClassWithCancellationSourceAndUsingTaskDotRunButNoParentReference : IDisposable
        {
            private CancellationTokenSource cts = new CancellationTokenSource();

            private readonly Task feedTask;

            public MyClassWithCancellationSourceAndUsingTaskDotRunButNoParentReference()
            {
                Logger.Log("New MyClassWithCancellationSourceAndUsingTaskDotRunButNoParentReference Instance");

                var token = cts.Token; // NB: by extracting the struct here (instead of in the lambda in the next line), we avoid the parent reference (via the cts member variable)
                feedTask = Task.Run(() => Background(token)); // token is a struct
            }

            private static void Background(CancellationToken token)  // must be static or else a reference to the parent class is passed
            {
                int i = 0;
                while (!token.IsCancellationRequested) // reference to cts means this class never gets finalized
                {
                    Logger.Log("Background task for MyClassWithCancellationSourceAndUsingTaskDotRunButNoParentReference running. " + i++);
                    Thread.Sleep(1000);
                }
            }

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

            protected virtual void Dispose(bool disposing)
            {
                cts.Cancel();

                if (disposing)
                {
                    feedTask.Wait();

                    feedTask.Dispose();

                    Logger.Log("MyClassWithCancellationSourceAndUsingTaskDotRunButNoParentReference Disposed");
                }
                else
                {
                    Logger.Log("MyClassWithCancellationSourceAndUsingTaskDotRunButNoParentReference Finalized");
                }
            }

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

        // finalizer doesn't get called until the app is exiting: background process keeps running
        public class MyClassWithCancellationSourceAndUsingTaskDotRun : IDisposable
        {
            private CancellationTokenSource cts = new CancellationTokenSource();

            private readonly Task feedTask;

            public MyClassWithCancellationSourceAndUsingTaskDotRun()
            {
                Logger.Log("New MyClassWithCancellationSourceAndUsingTaskDotRun Instance");
                //feedTask = Task.Factory.StartNew(Background, cts.Token);
                feedTask = Task.Run(() => Background());
            }

            private void Background()
            {
                    int i = 0;
                    while (!cts.IsCancellationRequested) // reference to cts & not being static means this class never gets finalized
                    {
                        Logger.Log("Background task for MyClassWithCancellationSourceAndUsingTaskDotRun running. " + i++);
                        Thread.Sleep(1000);
                    }
            }

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

            protected virtual void Dispose(bool disposing)
            {
                cts.Cancel();

                if (disposing)
                {
                    feedTask.Wait();

                    feedTask.Dispose();

                    Logger.Log("MyClassWithCancellationSourceAndUsingTaskDotRun Disposed");
                }
                else
                {
                    Logger.Log("MyClassWithCancellationSourceAndUsingTaskDotRun Finalized");
                }
            }

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


        // finalizer gets called eventually  (unless parent process is terminated)
        public class MyClassWithCancellationSourceAndNoLambda : IDisposable
        {
            private CancellationTokenSource cts = new CancellationTokenSource();

            private readonly Task feedTask;

            public MyClassWithCancellationSourceAndNoLambda()
            {
                Logger.Log("New MyClassWithCancellationSourceAndNoLambda Instance");
                feedTask = Task.Factory.StartNew(Background, cts.Token);
            }

            private static void Background(object state)
            {
                var cancelled = (CancellationToken)state;
                if (cancelled != null)
                {
                    int i = 0;
                    while (!cancelled.IsCancellationRequested)
                    {
                        Logger.Log("Background task for MyClassWithCancellationSourceAndNoLambda running. " + i++);
                        Thread.Sleep(1000);
                    }
                }
            }

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

            protected virtual void Dispose(bool disposing)
            {
                cts.Cancel();

                if (disposing)
                {
                    feedTask.Wait();

                    feedTask.Dispose();

                    Logger.Log("MyClassWithCancellationSourceAndNoLambda Disposed");
                }
                else
                {
                    Logger.Log("MyClassWithCancellationSourceAndNoLambda Finalized");
                }
            }

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


        // finalizer doesn't get called until the app is exiting: background process keeps running
        public class MyClassWithVolatileBoolCancellationFlag : IDisposable
        {
            class CancellationFlag { public volatile bool IsSet; }

            private CancellationFlag cf = new CancellationFlag();

            private readonly Task feedTask;

            public MyClassWithVolatileBoolCancellationFlag()
            {
                Logger.Log("New MyClassWithVolatileBoolCancellationFlag Instance");
                feedTask = Task.Factory.StartNew(() =>
                {
                    int i = 0;
                    while (!cf.IsSet)
                    {
                        Logger.Log("Background task for MyClassWithVolatileBoolCancellationFlag running. " + i++);
                        Thread.Sleep(1000);
                    }
                });
            }


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

            protected virtual void Dispose(bool disposing)
            {
                cf.IsSet = true;

                if (disposing)
                {
                    feedTask.Wait();

                    feedTask.Dispose();

                    Logger.Log("MyClassWithVolatileBoolCancellationFlag Disposed");
                }
                else
                {
                    Logger.Log("MyClassWithVolatileBoolCancellationFlag Finalized");
                }
            }

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

<强>更新

添加了一些测试(现在包含在上面):得出了与#34; usr&#34;相同的结论:如果有对父类的引用,那么终结器永远不会被调用(这是有道理的:存在活动参考,因此GC不会启动)