C#线程内访问线程外数据
是一个winform小程序。主要功能是:
1、在窗体运行前新建线程,在线程内开启socket服务。
2、当有新的连接时,在主窗口的一个textbox中打印相关信息。
主要问题:在线程内的数据无法在textbox中打印出来。
提示:“线程间操作无效: 从不是创建控件“textBox1”的线程访问它”
源代码:
namespace Server_2
{
public partial class Form1 : Form
{
Thread aThread = null;
private delegate void FlushClient(string s); //代理
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Text += ("正在开启server服务" + "\n" + ".......请稍候..." + "\n");
aThread = new Thread(new ThreadStart(StartSocketServer));
aThread.IsBackground = true;
aThread.Start();
textBox1.Text += ("server is start!" + "\n");
}
public void StartSocketServer()
{
IPAddress ip = IPAddress.Parse("192.168.168.163");
//IP地址跟端口的组合
IPEndPoint iep = new IPEndPoint(ip, 8001);
//创建Socket
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//绑定Socket
socket.Bind(iep);
//服务器已经做好接收任何连接的准备
socket.Listen(10);
while (true)
{
//执行accept方法
Socket Client = socket.Accept();
byte[] message = new byte[1024];
NetworkStream networkStream = new NetworkStream(Client);
int len = networkStream.Read(message, 0, message.Length);
//byte数组转换成string
string output = System.Text.Encoding.Unicode.GetString(message);
string pagehtml = ("一共从客户端接收了" + len.ToString() + "字节。接收字符串为:" + output);
ThreadFunction(pagehtml);
}
}
private void ThreadFunction(string s)
{
textBox1.Text = s;
}
}
}
namespace Server_2
{
public partial class Form1 : Form
{
Thread aThread = null;
private delegate void FlushClient(string s); //代理
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Text += ("正在开启server服务" + "\n" + ".......请稍候..." + "\n");
aThread = new Thread(new ThreadStart(StartSocketServer));
aThread.IsBackground = true;
aThread.Start();
textBox1.Text += ("server is start!" + "\n");
}
public void StartSocketServer()
{
IPAddress ip = IPAddress.Parse("192.168.168.163");
//IP地址跟端口的组合
IPEndPoint iep = new IPEndPoint(ip, 8001);
//创建Socket
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//绑定Socket
socket.Bind(iep);
//服务器已经做好接收任何连接的准备
socket.Listen(10);
while (true)
{
//执行accept方法
Socket Client = socket.Accept();
byte[] message = new byte[1024];
NetworkStream networkStream = new NetworkStream(Client);
int len = networkStream.Read(message, 0, message.Length);
//byte数组转换成string
string output = System.Text.Encoding.Unicode.GetString(message);
string pagehtml = ("一共从客户端接收了" + len.ToString() + "字节。接收字符串为:" + output);
ThreadFunction(pagehtml);
}
}
private void ThreadFunction(string s)
{
if (this.textBox1.InvokeRequired)//等待异步
{
FlushClient fc = new FlushClient(ThreadFunction);
this.Invoke(fc); //通过代理调用刷新方法
this.textBox1.Text = s;//这里
}
else
{
this.textBox1.Text = s;//这里
}
}
}
}