1

我正在 Winforms 中制作基于 ServiceStack 和 Redis 的聊天客户端。

我创建了一个消息集合,一旦我订阅它,我的应用程序就会冻结无响应。我是否可能遗漏了某些东西,或者是否缺少调用。或者是什么 .....

这是代码

 
public partial class frmChat :Form
{

public RedisClient redisClient = new RedisClient("192.168.111.50"); public bool registered = false; public string channelName = "letzChat"; public frmChat() { InitializeComponent(); } private void tbxUsername_KeyPress(object sender, KeyPressEventArgs e) { if (tbxUsername.Text.Trim() != string.Empty && e.KeyChar == (char) Keys.Enter) { IRedisSubscription rs = redisClient.CreateSubscription(); rs.OnSubscribe = chan => { chan_OnSubscribe(chan); }; rs.OnUnSubscribe = chan => { chan_OnUnSubscribe(chan); }; rs.OnMessage = (chan, msg) => { chan_OnMessage(chan, msg); }; rs.SubscribeToChannels(channelName); } } private void chan_OnMessage(string chan, string msg) { WriteLine(msg+"\n"); } private void chan_OnUnSubscribe(string chan) { registered = false; tbxUsername.Enabled = true; SendMessage(string.Format("User {0} registered to channel {1}", tbxUsername.Text, channelName)); } private void chan_OnSubscribe(string chan) { registered = true; tbxUsername.Enabled = false; } private void WriteLine(string msg) { foreach (var line in msg.Split('\n')) { tbxChat.Text += line + Environment.NewLine; } } private void btnSend_Click(object sender, EventArgs e) { SendMessage(); } private void tbxMessage_KeyPress(object sender, KeyPressEventArgs e) { if(e.KeyChar == (char)Keys.Enter) { SendMessage(); } } #region Message Sending private void SendMessage() { if (tbxMessage.Text.Trim() != string.Empty) { var m = string.Format("{0}: {1}", tbxUsername.Text, tbxMessage.Text); redisClient.PublishMessage(channelName, m); tbxMessage.Text = string.Empty; } } private void SendMessage(string msg) { redisClient.PublishMessage(channelName, msg); } #endregion

}

4

1 回答 1

1

我只是偶然发现了这个问题,因为我遇到了类似的问题并找到了解决方案。

显然,SubscribeToChannels() 和 SubscribeToChannelsMatching() 方法阻塞了线程。以下对我有用:

System.Threading.ThreadPool.QueueUserWorkItem(x =>
{
    GetSubscription().SubscribeToChannelsMatching("__keyevent*:*");
});

请参阅Redis Pub/Sub ServiceStack,取消线程以了解如何处理取消订阅。

于 2015-04-28T11:25:23.427 回答