我想实现一个运行后台任务的类,循环并更新该类的状态。一旦类超出范围,运行后台任务就没有任何价值,因此我想退出循环并允许任务完成并释放线程。
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>
,以使其超出范围,但我愿意接受解决方案。
如何检测“前景”对象超出范围并停止伴随的后台任务?