forked from microsoft/BotBuilder-Samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MemoryStore.cs
62 lines (54 loc) · 1.74 KB
/
MemoryStore.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
namespace Microsoft.BotBuilderSamples
{
/// <summary>
/// A thread safe implementation of the IStore abstraction intended for testing.
/// </summary>
public class MemoryStore : IStore
{
private IDictionary<string, (JObject, string)> _store = new Dictionary<string, (JObject, string)>();
private SemaphoreSlim _semaphoreSlim = new SemaphoreSlim(1, 1);
public async Task<(JObject content, string etag)> LoadAsync(string key)
{
try
{
await _semaphoreSlim.WaitAsync();
if (_store.TryGetValue(key, out ValueTuple<JObject, string> value))
{
return value;
}
return new ValueTuple<JObject, string>(null, null);
}
finally
{
_semaphoreSlim.Release();
}
}
public async Task<bool> SaveAsync(string key, JObject content, string eTag)
{
try
{
await _semaphoreSlim.WaitAsync();
if (eTag != null && _store.TryGetValue(key, out ValueTuple<JObject, string> value))
{
if (eTag != value.Item2)
{
return false;
}
}
_store[key] = (content, Guid.NewGuid().ToString());
return true;
}
finally
{
_semaphoreSlim.Release();
}
}
}
}