c# - 在 Twitch 中使用 IRC-Client 时 WPF-App 无法使用 [C#]

标签 c# wpf irc

我想设置我自己的 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/

相关文章:

wpf - 如何在 wpf xaml 中使用值转换器的特定属性

wpf - 更改 TabControl 中选定选项卡项的文本颜色?

c# - WPF 中的 XMLSerialization 问题

android - 选择正确的聊天协议(protocol)实现

java - 匹配并提取字符串中的数据

c# - 使用 C# 通过 Internet 进行最简单的双向通信

c# - 如何在方法中声明/设置静态变量

c# - EF代码优先,同一张表中有2个非空外键

c# - 在 matlab 代码中使用 C# dll 函数

c# - 通过代理连接到 IRC (.NET)