WCF 服务的线程问题

发布于 2024-12-17 07:16:34 字数 328 浏览 0 评论 0原文

我对 WCF 和线程都很陌生,所以请耐心等待。我设置了 WCF 服务。该服务有多个线程,所有线程都作用于单个数组。到目前为止,这没有问题。但是,该服务有一个方法,调用该方法时将返回数组。我的问题:

  1. 数组在通过WCF传输到客户端时被序列化。这是线程安全的操作吗?换句话说,我可以指望 WCF 在序列化该数组时阻止所有线程访问该数组吗?

  2. 如果我不能指望 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:

  1. 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?

  2. 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

本宫微胖 2024-12-24 07:16:34

不,WCF 运行时不会为您锁定数据。即使可以,它也不能阻止您访问另一个线程中的数组。

我认为获得此线程安全的唯一可能是在离开函数之前复制您在私有变量中返回的数据:

string[] Servicemethod()
{
  lock(myLock)
  {
      byte[] localCopy = new byte[myData.Length]; 
      Array.Copy(myData, localCopy, myData.Length);
      return localCopy;
  }
}

编辑

如果它不是复制大型数据结构的选项,另一个选择可能是不返回数组,而是实现 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:

string[] Servicemethod()
{
  lock(myLock)
  {
      byte[] localCopy = new byte[myData.Length]; 
      Array.Copy(myData, localCopy, myData.Length);
      return localCopy;
  }
}

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文