我想设置我自己的 TwitchBot,并具有良好的用户界面。但我遇到了一些麻烦:我对格式感到抱歉,但它没有很好地从 Visual Studio 复制它,而且这里的格式看起来很糟糕。
public class IrcClient
{
private string userName;
private string channel;
private TcpClient tcpClient;
private StreamReader inputStream;
private StreamWriter outputStream;
public IrcClient(string ip, int port, string userName, string password, string channel)
{
this.userName = userName;
this.channel = channel;
tcpClient = new TcpClient(ip, port);
inputStream = new StreamReader(tcpClient.GetStream());
outputStream = new StreamWriter(tcpClient.GetStream());
outputStream.WriteLine($"PASS {password}");
outputStream.WriteLine($"NICK {userName}");
outputStream.WriteLine($"USER {userName} 8 * :{userName}");
outputStream.WriteLine($"JOIN #{channel}");
outputStream.Flush();
}
public string ReadMessage()
{
return inputStream.ReadLine();
}
}
这是我设置 IRC 客户端的类(class)。然后我在 Visual Studio 中使用标准 WPF/C# 构建
private void Window_Loaded(object sender, RoutedEventArgs e)
{
System.Windows.Threading.DispatcherTimer dispatcherTimerChat = new System.Windows.Threading.DispatcherTimer();
dispatcherTimerChat.Tick += new EventHandler(dispatcherTimerChat_tick);
dispatcherTimerChat.Interval = new TimeSpan(500000);
dispatcherTimerChat.Start();
client = new IrcClient("irc.twitch.tv", 6667, "x", "x", "x");
var pinger = new Pinger(client);
pinger.Start();
}
private void dispatcherTimerChat_tick(object sender, EventArgs e)
{
Console.WirteLine(client.ReadMessage());
}
Window_loaded 在主窗口加载时被调用。在那里我只想接收聊天中写的内容。但用户界面严重滞后。当我将一些基本内容放入 XAML 代码(例如 Richttextbox)时,我什至无法在没有明显延迟的情况下写入其中。虽然降低 TimeSpan(x) 有帮助,但在人口合理的 channel 中读取聊天内容会出现问题。显然这里出了问题,但我不知道是什么。
Pinger 类每 5 分钟 ping 一次,这样我就不会被踢出 channel 并在自己的线程上运行。
这不是完整的代码,只是缺少运行 WPF 表单的最低限度的代码。
最佳答案
感谢aepot的评论我研究了异步编程。这个解决方案对我有用:
我添加了一个功能
private async Task<string> getChat()
{
string msg = await Task.Run(() => client.ReadMessage());
return msg;
}
并将调度程序函数更改为
private async void dispatcherTimerChat_tick(object sender, EventArgs e)
{
string msg = await getChat();
Console.WriteLine(msg);
}
这个tutorial一路上帮助了我。
关于c# - 在 Twitch 中使用 IRC-Client 时 WPF-App 无法使用 [C#],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62978965/