【发布时间】:2014-12-12 10:09:50
【问题描述】:
我需要使用 Interlocked 类处理我的 C# 应用程序中的锁。我有这样的代码:
class LogStruct
{
public Dictionary<string, ulong> domainName;
public Dictionary<string, ulong> URL;
public Dictionary<string, ulong> domainData;
public Dictionary<string, ulong> errorCodes;
public LogStruct()
{
domainName = new Dictionary<string, ulong> { };
URL = new Dictionary<string, ulong> { };
domainData = new Dictionary<string, ulong> { };
errorCodes = new Dictionary<string, ulong> { };
}
}
class CLogParser
{
string domainName = parameters[0];
string errorCode = matches[1].Value;
LogStruct m_logStruct;
...
public CLogParser()
{
m_logStruct = new LogStruct();
}
...
public void ThreadProc(object param)
{
if (m_logStruct.errorCodes.ContainsKey(fullErrCode))
{
lock (m_logStruct.errorCodes)
{
m_logStruct.errorCodes[fullErrCode]++;
}
}
}
}
而当我想在Interlocked类上替换ThreadProc中的锁时,例如:
public void ThreadProc(object param)
{
if (m_logStruct.errorCodes.ContainsKey(fullErrCode))
{
Interlocked.Increment(m_logStruct.errorCodes[fullErrCode]);
}
}
我收到此错误:
Error CS1502: The best overloaded method match for
`System.Threading.Interlocked.Increment(ref int)'
has some invalid arguments (CS1502) (projectx)
这个错误:
错误 CS1503:参数 #1' cannot convert
ulong 到 ref int' (CS1503) (projectx)
如何解决?
【问题讨论】:
-
将“ref”添加到调用站点。 (顺便说一句,这并不是说你的方法的其余部分一定会成功......无锁代码通常很难正确,即使是专家也是如此)。
-
@PeterDuniho,它没有帮助
-
啊...我明白了。您正在使用“ulong”。您只能将带符号的整数与 Interlocked.Increment 一起使用,而不是无符号的。
标签: c# locking interlocked-increment