Eva*_*sen 4 c# thread-safety task-parallel-library concurrentdictionary
我正在使用并发字典的GetOrAdd方法来检索值列表,然后引用我正在编辑它们的值列表.这样做是否可以线程安全?
我正在添加一个值的第一种方法和我正在清除列表的第二种方法.
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading.Tasks;
using Test.Web.Services;
namespace Test.Web.Messaging
{
public class Dispatch
{
private static readonly ConcurrentDictionary<string, IList<Message>> Messages = new ConcurrentDictionary<string, IList<Message>>();
public static void AddMessage(string id, Message value)
{
var msgs = Messages.GetOrAdd(id, new List<Message>());
msgs.Add(value);
}
public static void Send(string id)
{
var msgs = Messages.GetOrAdd(id, new List<Message>());
foreach (var msg in msgs)
{
Connection.Send(id, msg);
}
msgs.Clear();
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1291 次 |
| 最近记录: |