WCF 服务的线程问题
我对 WCF 和线程都很陌生,所以请耐心等待。我设置了 WCF 服务。该服务有多个线程,所有线程都作用于单个数组。到目前为止,这没有问题。但是,该服务有一个方法,调用该方法时将返回数组。我的问题:
数组在通过WCF传输到客户端时被序列化。这是线程安全的操作吗?换句话说,我可以指望 WCF 在序列化该数组时阻止所有线程访问该数组吗?
如果我不能指望 WCF 来执行此操作,那么我该如何手动实现它?我真的不明白 WCF 如何促进这一点,因为序列化是在我从方法调用返回后发生的。如何保证线程在我的方法返回数组之后、WCF 序列化数组之前不会修改该数组?
I'm new to both WCF and threading, so please bear with me. I have a WCF service set up. The service has multiple threads, all of which act upon a single array. This works without a problem so far. However, this service has a method, which, when called, will return the array. My questions:
The array is serialized when it is transferred to the client by WCF. Is this a thread safe operation? In other words, can I count on WCF to block all threads from accessing this array while it's being serialized?
If I can't count on WCF to do this, then how can I implement it manually? I don't really understand how WCF would facilitate this since the serialization happens after I return from my method call. How can I guarantee a thread will not modify the array after it's been returned by my method but before WCF serializes it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,WCF 运行时不会为您锁定数据。即使可以,它也不能阻止您访问另一个线程中的数组。
我认为获得此线程安全的唯一可能是在离开函数之前复制您在私有变量中返回的数据:
编辑
如果它不是复制大型数据结构的选项,另一个选择可能是不返回数组,而是实现 ISerialized 的自定义类的实例。
这样您就可以自己编写数据的线程安全序列化。
但在此之前,我会衡量额外副本的影响。
No, the WCF runtime won't lock the data for you. Even if it would, it can't keep you of from accessing the array in another thread.
I think the only possibilty to get this threadsafe is to copy the data you return in a private variable before leaving the function:
EDIT
If its not an option to copy large datastructures another option might be to not return an array but an instance of a custom class which implements
ISerializable
.That way you can write a threadsafe serialization of your data yourself.
But before doing that, i would measure the impact of the extra copy.