gpt4 book ai didi

c# - 在 C# 中使用 Redis 的聊天客户端卡住。任何人都可以提出任何建议吗?

转载 作者:IT王子 更新时间:2023-10-29 06:15:50 25 4
gpt4 key购买 nike

我正在用 Winforms 做一个基于 ServiceStack 和 Redis 的聊天客户端。

我创建了一个消息集合,并且在我订阅它后,我的应用程序立即停止响应。我是否可能遗漏了什么或者是否缺少调用。或者什么.....

这是代码

 
public partial class frmChat :Form
{<p></p>

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

最佳答案

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

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

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

参见 Redis Pub/Sub ServiceStack, cancelling the thread了解如何处理退订。

关于c# - 在 C# 中使用 Redis 的聊天客户端卡住。任何人都可以提出任何建议吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16057846/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com