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}
开始。如果我首先使用string.Format(),我没有问题。发生了什么事?
答案 0 :(得分:11)
问题在于你没有调用你认为的过载。您正在调用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);
或者,您可能希望创建自己的便捷方法,不具有额外的,无用的(在您的情况下)重载。
答案 1 :(得分:0)
我知道这是一个旧线程,并且与问题无关,但是对于.NET的较新版本,您也可以使用插值:
Debug.WriteLine($"Queued batch item: {bm.BatchName}");
如果您最后还是在这里,是的,它是线程安全的。这不是,我发现很难:
Console.WriteLine($"Queued batch item: {bm.BatchName}");