Skip to content

Instantly share code, notes, and snippets.

@TheFo2sh
Last active September 4, 2020 20:57
Show Gist options
  • Save TheFo2sh/a65a4d599591cf5a1bc72533fac5d91e to your computer and use it in GitHub Desktop.
Save TheFo2sh/a65a4d599591cf5a1bc72533fac5d91e to your computer and use it in GitHub Desktop.
using System;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Couchbase.Lite;
namespace ChannelQueue
{
class DocumentWriter : IDisposable
{
private readonly MutableDocument _document;
private readonly Thread _currentThread;
private readonly
Channel<(string key, string value, TaskCompletionSource<IMutableDictionary> taskCompletionSource)> _channel;
public DocumentWriter(MutableDocument document)
{
_document = document;
_channel = Channel.CreateUnbounded<(string key, string value, TaskCompletionSource<IMutableDictionary> taskCompletionSource)>();
_currentThread = new Thread(Start);
_currentThread.Start();
}
private async void Start()
{
while (await _channel.Reader.WaitToReadAsync())
{
var item = await _channel.Reader.ReadAsync();
var result = _document.SetString(item.key, item.value);
item.taskCompletionSource.SetResult(result);
}
}
public async Task<IMutableDictionary> WriteToDocumentAsync(string key, string value)
{
var taskCompletionSource = new TaskCompletionSource<IMutableDictionary>();
await _channel.Writer.WriteAsync((key, value, taskCompletionSource));
return await taskCompletionSource.Task;
}
public void Dispose()
{
_channel.Writer.Complete();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment