Blazor服务中可以使用ConcurrentDictionary类来实现异步字典的操作。示例如下:
在服务端:
using System.Collections.Concurrent;
using System.Threading.Tasks;
public class MyService : IMyService
{
private ConcurrentDictionary _dictionary = new ConcurrentDictionary();
public async Task GetValueAsync(int key)
{
if (_dictionary.TryGetValue(key, out string value))
{
return value;
}
return await Task.FromResult(null);
}
public async Task AddOrUpdateAsync(int key, string value)
{
_dictionary.AddOrUpdate(key, value, (k, v) => value);
await Task.CompletedTask;
}
public async Task RemoveAsync(int key)
{
_dictionary.TryRemove(key, out string value);
await Task.CompletedTask;
}
}
在客户端:
@page "/"
@inject IMyService MyService
@if (_value == null)
{
}
else
{
Value: @_value
}
@code {
private int _key;
private string _value;
private async Task GetValue()
{
_value = await MyService.GetValueAsync(_key);
}
private async Task AddOrUpdate()
{
await MyService.AddOrUpdateAsync(_key, _value);
}
private async Task Remove()
{
await MyService.RemoveAsync(_key);
}
}