作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
Debug.WriteLine()线程安全吗?
根据this,它是线程安全的。但是,在我的多线程程序中,我得到了一些奇怪的输出。
例如:
代码
// these statements are found throughout the program
Debug.WriteLine("Polled database. {0} batch items retrieved.", items.Count());
Debug.WriteLine("Queued batch item: {0}", bm.BatchName);
Debug.WriteLine("Discarded batch item: {0} already queued.", bm.BatchName);
Debug.WriteLine("Creating task for batch item: {0}", bm.BatchName);
Debug.WriteLine("Removed batch item from processing items collection: {0}", bm.BatchName);
Debug.WriteLine("Could not remove batch item from processing items collection: {0}", bm.BatchName);
Debug.WriteLine("Begin Processing: {0}", bm.BatchName);
Debug.WriteLine("End Processing: {0}", bm.BatchName);
输出
"Polled database. 0 batch items retrieved."
"Polled database. 0 batch items retrieved."
"Polled database. 0 batch items retrieved."
"Polled database. 0 batch items retrieved."
"Polled database. 1 batch items retrieved."
"ronnie's batch: Queued batch item: {0}"
"ronnie's batch: Creating task for batch item: {0}"
"Begin Processing: ronnie's batch"
"Polled database. 1 batch items retrieved."
"ronnie's batch: Discarded batch item: {0} already queued."
"End Processing: ronnie's batch"
"ronnie's batch: Removed batch item from processing items collection: {0}"
"Polled database. 0 batch items retrieved."
您可以看到
ronnie's batch: Queued batch item: {0}
开始让事情变得毫无意义了。到底是怎么回事?
最佳答案
问题在于您没有调用您认为的重载。您正在调用 Debug.WriteLine(string, string)
,它将第一个参数用作消息,将第二个参数用作类别,而不是格式参数。
解决此问题的最简单方法是将参数强制转换为object
,以强制其使用 Debug.WriteLine(string, params object[])
重载:
Debug.WriteLine("Queued batch item: {0}", (object) bm.BatchName);
Debug.WriteLine("Queued batch item: {0}", new object[] { bm.BatchName });
string.Format
来调用
Debug.WriteLine(string)
重载:
Debug.WriteLine(string.Format("Queued batch item: {0}", bm.BatchName));
Debug.WriteLine("Queued batch item: " + bm.BatchName);
关于.net - Debug.WriteLine()线程安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6959733/
我是一名优秀的程序员,十分优秀!