我有一个字典,其中包含数据,我有处理并发客户端请求的线程。我希望某些客户端请求在需要时更改字典中的值,但不知道在处理线程和类时如何解决范围问题。C#更新字典在不同的类
的什么,我试图做一个简单的例子如下:
class Program
{
public static Dictionary<string, int> teamInformation = new Dictionary<string, int>();
static void Main(string[] args)
{
runserver();
}
static void runServer()
{
//connection stuff
while(true)
{
threadRequest = new Handler();
Thread t = new Thread (() => threadRequest.clientInteraction(connection));
t.Start();
}
}
class Handler
{
public void clientInteraction(Socket connection)
{
//does stuff
teamInformation.Add(pTeamName, 0); //where pTeamName has been read from the client input
}
}
我怎么会去结交Handler类更改词典(这需要所有线程可访问)?
我不知道如何为线索编制索引或者至少在词典条目中标记它们。我很难找出将特定值发送到特定线程的方法。
使用[ConcurrentDictionary](https://msdn.microsoft.com/zh-cn/library/dd287191( v = vs.110).aspx) – stuartd
@stuartd这似乎正是我需要感谢。我现在正在研究它。但是我是否需要每次在Handler类中声明Concurrent Dictionary?是否会为所有线程编辑具有相同名称的字典?或者只是简单地创建与每个线程相关的多个并发字典 – James