3

I have the following simple class:

public sealed class TimeStampTestViewModel : ObservableObject
{
    private CancellationTokenSource cancellationSource; 

    public TimeStampTestViewModel()
    {
        this.cancellationSource = new CancellationTokenSource();
        PeriodicTimeStampChanged(cancellationSource.Token);
    }

    public string TimeStamp
    {
        get 
        {
            return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }
    }

    private async void PeriodicTimeStampChanged(CancellationToken token)
    {
        while (!token.IsCancellationRequested)
        {
            RaisePropertyChanged("TimeStamp");
            await Task.Delay(500, token);
        }
    }
}

Will an instance of this class ever be garbage collected? Or will the presence of the infinite running task block garbage collection?

Oliver
  • 11,297
  • 18
  • 71
  • 121

2 Answers2

1

This will not be GC'ed because the task is always rooted.

  1. If it's inside of the delay there is a hidden Timer instance that itself is a root. The rooting chain goes like this: timer -> callback -> async state machine -> TaskCompletionSource -> Task.
  2. If it's currently executing the thread that it runs on is the root.

This is not generalizable. For example await new TCS().Task; will be GC'ed. There is no root.

usr
  • 168,620
  • 35
  • 240
  • 369
0

No, I don't think it can be garbage collected.

The reason behind that the Garbage collector will notify for the object to free from memory untill and unless they are not in use. Since if the object are regularly the part of the task and is reqularly in use the object cant be released.