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
|
|
|
|
|
{
|
2020-04-22 04:13:07 +00:00
|
|
|
|
private readonly ConcurrentStack<T> _collection = new ConcurrentStack<T>();
|
2020-03-29 03:29:27 +00:00
|
|
|
|
private bool isDisposed = false;
|
2020-04-22 04:13:07 +00:00
|
|
|
|
|
|
|
|
|
public int Count => _collection.Count;
|
2020-03-29 03:29:27 +00:00
|
|
|
|
|
|
|
|
|
public void Add(T val)
|
|
|
|
|
{
|
2020-04-22 04:13:07 +00:00
|
|
|
|
_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;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|