jim*_*rix 2 c# user-interface multithreading
我正在尝试创建一个基本的IRC客户端...但我的问题是让文本显示在RTF框中而没有它滞后
我决定使用线程,我想更新线程中的RTF框,但我不能因为它给出了关于RTF框元素不是静态的错误?
任何见解?如果你们想要,我会粘贴代码
好的,这里是代码(编辑凹凸?)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Net;
namespace IrcClient
{
public partial class mainWindow : Form
{
static IRC client;
static string newLine, oldLine;
public mainWindow()
{
InitializeComponent();
}
private void main()
{
}
private void mainWindow_Load(object sender, EventArgs e)
{
client = new IRC("irc.freenode.net" ,6667, "jimi__hendrix");
new Thread(new ThreadStart(update)).Start();
}
private static void update()
{
newLine = client.sr.ReadLine();
Thread.Sleep(50);
}
private void btnSend_Click(object sender, EventArgs e)
{
client.privmsg(inputBox.Text);
messageBox.AppendText(inputBox.Text + "\n");
inputBox.Text = "";
}
private void timer1_Tick(object sender, EventArgs e)
{
if (newLine != oldLine)
{
messageBox.AppendText(newLine + "\n");
oldLine = newLine;
}
}
}
class IRC
{
TcpClient connection;
NetworkStream stream;
public StreamWriter sw;
public StreamReader sr;
string nick;
public IRC(string server, int port, string Nick)
{
try
{
connection = new TcpClient(server, port);
stream = connection.GetStream();
sr = new StreamReader(stream);
sw = new StreamWriter(stream);
nick = Nick;
sw.WriteLine("PASS " + "caruso11");
sw.Flush();
sw.WriteLine("NICK " + nick);
sw.Flush();
sw.WriteLine("USER Jimi__Hendrix 8 irc.freenode.net :Jimi__Hendrix");
sw.Flush();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
public void privmsg(string msg)
{
sw.WriteLine(msg);
sw.Flush();
}
public void parse(string msg)
{
}
}
}
Run Code Online (Sandbox Code Playgroud)
一些方法是空白的,一些代码可以清理,但我想先完成这个...还有,视觉工作室生成的代码设置窗口
通常,由于Windows的限制,尝试从主线程以外的线程更新控件将不起作用.如果需要从工作线程调用方法或在RTF框上设置属性,则可能需要使用Invoke或BeginInvoke.这可能如下所示:
void MyThreadMethod()
{
// stuff
this.rtfBox.BeginInvoke( (MethodInvoker)(()=> this.rtfBox.Text = "foo") );
// stuff
}
Run Code Online (Sandbox Code Playgroud)
编辑:正如其他人所指出的,如果由于关于控件不是静态的错误而实际上无法编译,那么您可能尝试从静态函数引用成员变量,这是非法的.发布代码将有助于缩小问题范围.
| 归档时间: |
|
| 查看次数: |
4229 次 |
| 最近记录: |