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

发布于 2024-11-18 02:43:13 字数 3131 浏览 3 评论 0原文

我想实现一个网络聊天。

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

作为基础,我使用 这篇博文 这样,异步操作就完成了。

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

[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 中的想法相同

: 顺便说一句,当没有收到任何消息时,等待超时就会生效,响应就会返回。所以它似乎在某个地方崩溃了。知道如何记录这个吗?

I want to implement a webchat.

The backend is a dual WCF channel. Dual channel works in the console or winforms,
and it actually works on the web. I can at least send and receive messages.

As a base I used this blog post
so, the async operation completes.

When i debug the result, I see that the messages are all ready to send to the browser.

[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);
  }
}

But nothing is actually sent.

Checking Fiddler, I see the request but I never get a response.

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

I also had to set the SessionStateBehaviour to Readonly, otherwise the async operation would block the whole page.

EDIT:
Here is the 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);
    }
  }
}

it`s the same idea as the in the refered blog post

EDIT2:
Btw, when nothing is received, so the wait timeout comes into play, the reponse returns. so it seems to crash somewhere. any idea how to log this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

余生共白头 2024-11-25 02:43:13

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

I changed the jQUERY request (see original blog post) from POST to GET. That fixes it.

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