gpt4 book ai didi

.net - Debug.WriteLine()线程安全吗?

转载 作者:行者123 更新时间:2023-12-04 13:54:17 31 4
gpt4 key购买 nike

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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com