【问题标题】:WCF Server (net-tcp) against backand running non-thread-safe unmanaged codeWCF 服务器 (net-tcp) 针对 backand 运行非线程安全的非托管代码
【发布时间】:2011-09-08 19:16:03
【问题描述】:

我的任务是为现有(会话完整)服务编写 WCF 服务主机(服务器)——到目前为止并不难。该服务是一个 ADO 代理服务器,它将 ADO 连接代理到各种后端数据库。这在大多数情况下效果很好,但我需要支持的 ADO .NET 数据提供程序之一是作为连接到非线程安全的非托管代码 (C) API 的驱动程序实现的。

优选的解决方案,使代码线程安全或实现线程安全的托管驱动程序目前已不在讨论范围内。有人建议我可以将多个进程作为一种后端或二级代理来运行,但是当我第一次听到它时,这让我觉得实现它是一场噩梦,在我进行试验实现时更是如此。

我的问题是,我在这里缺少另一个解决方案吗?到目前为止,我一直在使用 ConncurrencyMode.Single 和 UseSynchronization = true,但问题的真正核心是会话和非线程安全的后端。到目前为止还没有运气。我是否坚持代理与多个进程的连接,还是其他人可以提出更优雅的解决方案?

谢谢!

【问题讨论】:

    标签: multithreading wcf multiprocessing


    【解决方案1】:

    我会做的(实际上我自己也遇到过这种情况)是启动一个专用线程,该线程将为分派到非托管 API 的请求提供服务。该线程将坐在那里等待请求消息。请求消息将指示线程对 API 执行某些操作。一旦线程完成处理请求,它就会构造一个响应消息。响应消息将包含返回的数据。如果您使用BlockingCollection 将请求和响应消息排队,则该模式非常简单。

    public class SingleThreadedApiAbstraction
    {
      private BlockingCollection<Request> requests = new BlockingCollection<Request>();
      private BlockingCollection<Response> responses = new BlockingCollection<Response>();
    
      public SingleThreadedApiAbstraction()
      {
        var thread = new Thread(Run);
        thread.IsBackground = true;
        thread.Start();
      }
    
      public /* Return Type */ SomeApiMethod(/* Parameters */)
      {
        var request = new Request(/* Parameters */);
        requests.Add(request); // Submit the request.
        var response = responses.Take(); // Wait for the response.
        return response.ReturnValue;
      }
    
      private void Run()
      {
        while (true)
        {
          var request = requests.Take(); // Wait for a request.
          // Forward the request parameters to the API.
          // Then construct a response object with the return value.
          var response = new Response(/* Returned Data */);
          responses.Add(response); // Publish the response.
        }
      }
    }
    

    这个想法是 API 只能通过这个专用线程访问。拨打SomeApiMethod 的方式或是谁都没有关系。需要注意的是,如果队列为空,Take 会阻塞。 Take 方法是神奇发生的地方。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-23
      相关资源
      最近更新 更多