wabbajack/Wabbajack.Common/AsyncBlockingCollection.cs

44 lines
1.1 KiB
C#
Raw Normal View History

2020-03-29 03:29:27 +00:00
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace Wabbajack.Common
{
public class AsyncBlockingCollection<T> : IDisposable
{
private readonly ConcurrentStack<T> _collection = new ConcurrentStack<T>();
2020-03-29 03:29:27 +00:00
private bool isDisposed = false;
public int Count => _collection.Count;
2020-03-29 03:29:27 +00:00
public void Add(T val)
{
_collection.Push(val);
2020-03-29 03:29:27 +00:00
}
public async ValueTask<(bool found, T val)> TryTake(TimeSpan timeout, CancellationToken token)
{
var startTime = DateTime.Now;
while (true)
{
2021-03-11 23:01:16 +00:00
if (_collection.TryPop(out var result))
2020-03-29 03:29:27 +00:00
{
return (true, result);
}
if (DateTime.Now - startTime > timeout || token.IsCancellationRequested || isDisposed)
2020-11-18 11:37:31 +00:00
return (false, default)!;
2020-03-29 03:29:27 +00:00
await Task.Delay(100);
}
}
public void Dispose()
{
isDisposed = true;
}
}
}