我正在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
}
答案 0 :(得分:1)
我只是偶然发现了这个问题,因为我遇到了类似的问题并找到了解决方案。
显然,SubscribeToChannels()和SubscribeToChannelsMatching()方法会阻塞线程。以下对我有用:
System.Threading.ThreadPool.QueueUserWorkItem(x =>
{
GetSubscription().SubscribeToChannelsMatching("__keyevent*:*");
});
请参阅Redis Pub/Sub ServiceStack, cancelling the thread了解如何处理取消订阅。