问题描述
我用
ThreadPool.QueueUserWorkItem(O => service.Method(ARG1,ARG2))调用服务的方法;
服务对象有loggingService与我所用Spring.Net
Service has object 'loggingService' with I was get using Spring.Net
私人只读ILoggingService loggingService = ObjectBuilder.GetObjectByName(LoggingService);
LoggingService'类是单身。它写入日志信息,以log.txt的
'LoggingService' class is singleton. It writes log info to log.txt.
当我尝试在这种服务方法调用loggingService.Info(测试),我得到异常:文件是由忙另一个进程。
When I try to call loggingService.Info("test") in this service method, I get exception: file is busy by another process.
我如何可以访问到loggingService?
How can I access to the loggingService?
推荐答案
你的单显然是每个线程。结果
你需要传递 LoggingService
在线程之间的某种方式。
Your singleton is apparently per-thread.
You will need some way of passing the LoggingService
across threads.
例如,你可以在原来的线程设置 service.loggingService
。
For example, you could set service.loggingService
in the original thread.
另外,你也许可以配置Spring.Net,使之成为非线程本地单身。
Alternatively, you might be able to configure Spring.Net to make it a non-thread-local singleton.
请注意,你必须LoggingService是线程安全的,或者你会得到奇怪的错误在运行时。
Note that your LoggingService must be thread-safe, or you'll get strange errors at runtime.
这篇关于从另一个线程访问singleton对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!