运行后台任务,直到对象超出范围

时间:2018-08-17 11:19:21

标签: c# task-parallel-library

我想实现一个运行后台任务的类,循环并更新该类的状态。一旦类超出范围,运行后台任务就没有任何价值,因此我想退出循环并允许任务完成并释放线程。

public class ValueProvider
{
    private ConfigurationReloadToken _reloadToken = new ConfigurationReloadToken();

    public string Value {get; private set;}

    public IChangeToken ChangeToken => _reloadToken;

    public void Load()
    {
        // Load the initial value.
        Value = "Foo";            

        // Watch for changes to and reload the value.
        WatchForChanges();
    }

    private void WatchForChanges() => Task.Run(WatchAsync);

    private async Task WatchAsync()
    {   
        var stillInScope = true;
        while(stillInScope)
        {
            // Watch for new values.
            Value = await LoadNewValueAsync();

            // Signal a change.
            OnReload();
        }
    }

    private async Task<string> LoadNewValueAsync()
    {
        // Simulate an actual lookup which blocks until a new value is available.
        await Task.Delay(TimeSpan.FromSeconds(30));

        return "Bar";
    }

    private void OnReload()
    {
        var previousToken = Interlocked.Exchange(
            ref _reloadToken,
            new ConfigurationReloadToken());
        previousToken.OnReload();
    }
}

由于创建的Task引用了ValueProvider,因此实例将永远不会超出范围。解决方案可能必须包括通过ValueProvider从后台任务访问WeakReference<T>,以使其超出范围,但我愿意接受解决方案。

如何检测“前景”对象超出范围并停止伴随的后台任务?

0 个答案:

没有答案