[英]Is Debug.WriteLine() thread safe?
Debug.WriteLine()线程安全吗?
根据这个 ,它是线程安全的。 但是,在我的多线程程序中,我得到一些奇怪的输出。
例如:
// 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}
事件开始ronnie's batch: Queued batch item: {0}
如果我首先使用string.Format(),我没有问题。 到底是怎么回事?
问题是你没有调用你认为的过载。 您正在调用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($"Queued batch item: {bm.BatchName}");
此外,如果你到这里结束,是的,它是线程安全的。 这不是,我发现了困难的方法:
Console.WriteLine($"Queued batch item: {bm.BatchName}");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.