Last active
September 4, 2020 20:57
-
-
Save TheFo2sh/a65a4d599591cf5a1bc72533fac5d91e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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