【发布时间】:2013-07-01 22:21:00
【问题描述】:
在我的静态类中,我有这个:
static var cache = new ConcurrentDictionary<string, object>();
在线程 #1 我这样做:
cache.TryAdd (stringFromSomewhere, newlyCreatedObject);
Console.WriteLine(stringFromSomewhere); // Outputs "abc"
在线程 #1 之后几秒钟,在线程 #2:
if(cache.ContainsKey(stringFromSomewhereElse))
Console.WriteLine("Yes, it exists.");
else
Console.WriteLine("This did not exist: " + stringFromSomewhereElse);
它输出“这不存在:abc”
然后在 Thread #2 之后的 Thread #3 几秒钟:
foreach(var kvp in cache)
{
Console.WriteLine("string: " + kvp.Key);
if(cache.ContainsKey(kvp.Key))
Console.WriteLine("Yes, it exists.");
else
Console.WriteLine("This did not exist: " + kvp.Key);
}
我得到输出“字符串:abc”和“是的,它存在。”
在线程 #1 中,我使用 MD5 创建字符串,如下所示:
Convert.ToBase64String (md5.ComputeHash(Encoding.ASCII.GetBytes(value)))
在线程 #2 中,我从字节流中获取字符串,该字符串使用 UTF8 编码写入其中,然后再次使用 UTF8 编码从字节中读取字符串。
在线程 #3 中,我通过循环 ConcurrentDictionary 来获取字符串。
我在这里缺少什么?据我所知,线程#2 的行为应该与线程#3 一样。
我有两种可能性,我认为这两种可能性都很大:
- 这是我不知道的某种同步问题吗?
- 或者字符串有什么不同?当我将它输出到控制台时,它并没有什么不同。
有人有其他想法或解决方案吗?
编辑:
我像这样将数据写入流:
string data = System.Web.HttpUtility.UrlEncode(theString);
byte[] buffer = Encoding.UTF8.GetBytes (data);
NetworkStream stream = client.GetStream(); // TcpClient client;
stream.Write (buffer, 0, buffer.Length);
然后我像这样从流中读取数据:
string data = "";
NetworkStream stream = client.GetStream(); // TcpClient client;
byte[] bytes = new byte[4096];
do {
int i = stream.Read (bytes, 0, bytes.Length);
data += Encoding.UTF8.GetString (bytes, 0, i);
} while(stream.DataAvailable);
string theString = HttpUtility.UrlDecode(data);
【问题讨论】:
-
您必须提供更多代码。
-
你想看什么?
-
最小代码sn-p,其行为与描述相同。
-
我添加了编辑,我描述了如何将字符串写入流并读回。
-
当你将它输出到控制台时,输出长度并在字符串周围加上引号。听起来可能有一些空格或不可打印的字符。类似
Console.WriteLine("This did not exist: '{0}', Length={1}", stringFromSomewhereElse, stringFromSomewhereElse.Length);
标签: c# string multithreading stream concurrentdictionary