简体   繁体   English

来自单独线程的WCF响应

[英]WCF response from separate thread

public interface IEventDismiss
{
    [OperationContract]
    [return:MessageParameter(Name="response")]
    [XmlSerializerFormat]
    Response ProcessRequest(Request request);
}

Hello, 你好,

Above is my WCF implementation in C# and it is pretty straight forward. 上面是我在C#中的WCF实现,非常简单。 However, it becomes a little more complicated when I receive the request and pass it on to another thread to process to produce the response and finally send this response back. 但是,当我接收到请求并将其传递给另一个线程进行处理以生成响应并最终将该响应发送回时,情况变得有些复杂。

My algorithm is: 我的算法是:

  1. Get the request. 获取请求。
  2. Pass it on to a separate thread to process by putting onto a static queue for other thread. 将其传递到单独的线程上,以放入其他线程的静态队列中进行处理。
  3. Once thread finish processing, it put the response object onto a static queue. 一旦线程完成处理,它将响应对象放入静态队列。
  4. In my function ProcessRequest I have a while loop that dequeue this response and send it back to the requester. 在我的ProcessRequest函数中,我有一个while循环,该循环使该响应出队并将其发送回请求者。

     public Response ProcessRequest (Request request) { bool sWait = true; Response sRes = new Response(); ResponseProcessor.eventIDQueue.Enqueue(request.EventID); while (sWait) { if (ResponseProcessor.repQ.Count > 0) { sRes = ResponseProcessor.repQ.Dequeue(); sWait = false; } } return sRes; } 

Now, before everyone start to grill me, I am too realized this is bad practice and that's why I ask the question here in hoping to get better way to do this. 现在,在所有人开始烧烤之前,我也意识到这是一种不好的做法,这就是为什么我在这里提出问题,以期寻求更好的方法来做到这一点。 I realized with the current code I have the following issues: 我意识到,使用当前代码,我会遇到以下问题:

My while loops maybe in a continue loop and thus eating up the CPU if it has no sleep() in between. 我的while循环可能处于continue循环中,因此如果它们之间没有sleep(),则会吞噬CPU。 My response queue may contains the wrong response back due to the nature of async call. 由于异步调用的性质,我的响应队列可能包含错误的响应。

So I have two questions: 所以我有两个问题:

  1. Is there a way to put sleep in the while loop to eliminate the high CPU usage? 有没有一种方法可以使while循环进入睡眠状态,以消除高CPU使用率?
  2. Is there a better way to do this? 有一个更好的方法吗?

There's not point in doing this in the first place. 首先,这样做没有意义。 Rather than having the current thread sitting around doing nothing while it waits for another queue to compute the work (while eating up tons of CPU cycles anyway), just compute the response in the current thread and send it back. 与其让当前线程无所事事,而它等待另一个队列来计算工作(无论如何都要消耗大量的CPU周期), 只需在当前线程中计算响应并将其发送回即可。 You are gaining nothing by queuing it for another thread to handle. 通过将其排队供另一个线程处理,您一无所获。

You are also using queue objects that cannot be safely accessed from multiple threads, so in addition to being extremely inefficient, it's also subject to race conditions that can mean it won't even work. 您还使用不能被多个线程安全地访问队列对象,所以除了是极其低效的,它也受到种族这可能意味着它甚至不能正常工作的条件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM