异步操作完成,但结果不会发送到浏览器

时间:2011-06-30 20:59:44

标签: c# asp.net-mvc-3 asynccontroller

我想实施网络聊天。

后端是双WCF通道。双通道可在控制台或winforms中工作, 它实际上在网络上工作。我至少可以发送和接收消息。

作为基础,我使用了this blog post 所以,异步操作完成。

当我调试结果时,我看到消息都已准备好发送到浏览器。

[AsyncTimeout(ChatServer.MaxWaitSeconds * 1020)] // timeout is a bit longer than the internal wait
public void IndexAsync()
{
  ChatSession chatSession = this.GetChatSession();
  if (chatSession != null)
  {
    this.AsyncManager.OutstandingOperations.Increment();
    try
    {
      chatSession.CheckForMessagesAsync(msgs =>
      {
        this.AsyncManager.Parameters["response"] = new ChatResponse { Messages = msgs };
        this.AsyncManager.OutstandingOperations.Decrement();
      });
    }
    catch (Exception ex)
    {
      Logger.ErrorException("Failed to check for messages.", ex);
    }
  }
}

public ActionResult IndexCompleted(ChatResponse response)
{
  try
  {
    if (response != null)
    {
      Logger.Debug("Async request completed. Number of messages: {0}", response.Messages.Count);
    }
    JsonResult retval = this.Json(response);
    Logger.Debug("Rendered response: {0}", retval.);
    return retval;
  }
  catch (Exception ex)
  {
    Logger.ErrorException("Failed rendering the response.", ex);
    return this.Json(null);
  }
}

但实际上没有发送任何内容。

检查Fiddler,我看到了请求,但我从未收到回复。

[SessionState(SessionStateBehavior.ReadOnly)]  
public class ChatController : AsyncController

我还必须将SessionStateBehaviour设置为Readonly,否则异步操作会阻止整个页面。

编辑: 这是CheckForMessagesAsync:

public void CheckForMessagesAsync(Action<List<ChatMessage>> onMessages)
{
  if (onMessages == null)
    throw new ArgumentNullException("onMessages");

  Task task = Task.Factory.StartNew(state =>       
  {
    List<ChatMessage> msgs = new List<ChatMessage>();
    ManualResetEventSlim wait = new ManualResetEventSlim(false);
    Action<List<ChatMessage>> callback = state as Action<List<ChatMessage>>;
    if (callback != null)
    {
      IDisposable subscriber = m_messages.Subscribe(chatMessage =>
      {
        msgs.Add(chatMessage);
        wait.Set();
      });
      bool success;
      using (subscriber)
      {
        // Wait for the max seconds for a new msg
        success = wait.Wait(TimeSpan.FromSeconds(ChatServer.MaxWaitSeconds));              
      }
      if (success) this.SafeCallOnMessages(callback, msgs);
      else this.SafeCallOnMessages(callback, null);
    }        
  }, onMessages);
}
private void SafeCallOnMessages(Action<List<ChatMessage>> onMessages, List<ChatMessage> messages)
{
  if (onMessages != null)
  {
    if (messages == null)
      messages = new List<ChatMessage>();
    try
    {
      onMessages(messages);
    }
    catch (Exception ex)
    {
      this.Logger.ErrorException("Failed to call OnMessages callback.", ex);
    }
  }
}

它与提到的博客文章中的想法相同

EDIT2: 顺便说一句,当没有收到任何东西时,等待超时发挥作用,响应返回。所以它似乎在某处崩溃。任何想法如何记录这个?

1 个答案:

答案 0 :(得分:1)

我将jQUERY请求(请参阅原始博文)从POST更改为GET。这解决了它。