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)
{
if (_collection.TryPop(out T result))
2020-03-29 03:29:27 +00:00
{
return (true, result);
}
if (DateTime.Now - startTime > timeout || token.IsCancellationRequested || isDisposed)
return (false, default);
await Task.Delay(100);
}
}
public void Dispose()
{
isDisposed = true;
}
}
}