读书人

小弟我编写的监听程序c# 但是程序运行

发布时间: 2013-07-01 12:33:04 作者: rapoo

我编写的监听程序c# 但是程序运行后一点窗体就会卡死 怎么解决啊 那为大神帮我看看 怎么改
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;
using System.Net.Sockets;
using System.Threading;

namespace 聊天__qq群
{
public partial class Form1 : Form
{

bool done = false;

public Form1()
{
InitializeComponent();
}
private void StartListener()
{
UdpClient listener = new UdpClient(int.Parse(textBox1.Text.ToString().Trim())); //使用UDP协议??
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, int.Parse(textBox1.Text.ToString().Trim())); //任意IP,
try
{
while (!done)//使用永真循环另其一直处于监听状态
{

byte[] bytes = listener.Receive(ref groupEP);
string strIP;
strIP = "信息来自" + groupEP.Address.ToString();//获得发信人的IP
string strInfo = Encoding.GetEncoding("gb2312").GetString(bytes, 0, bytes.Length);//获得信息
MessageBox.Show(strInfo, strIP);
}
}
catch (Exception e)
{ Console.WriteLine(e.ToString()); }
finally { listener.Close(); }

}
private void Form1_Load(object sender, EventArgs e)
{


}

private void button1_Click(object sender, EventArgs e)
{
StartListener(); //调用监听方法


}


}
}
这个就这么改吗 加到哪里就可以了啊

private void button1_Click(object sender, EventArgs e)
{
ThreadPool.QueueUserWorkItem(StartListener, null); //调用监听方法
}

好像是楼上的意思
[解决办法]
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;

注意:要加上这句。 在这加吧。

public Form1()
{
InitializeComponent();
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
}

[解决办法]

引用:
Quote: 引用:

System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;

注意:要加上这句。 在这加吧。

public Form1()
{
InitializeComponent();
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
}
还是不行啊 还是会出现错误啊



你那个方法加个参数

private void StartListener(object obj)

[解决办法]
引用:
Quote: 引用:

Quote: 引用:

Quote: 引用:

System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;

注意:要加上这句。 在这加吧。

public Form1()
{
InitializeComponent();
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
}
还是不行啊 还是会出现错误啊



你那个方法加个参数

private void StartListener(object obj)
这个参数下面要写什么东西吗




你可以不用

引用:
Quote: 引用:

Quote: 引用:

Quote: 引用:

System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;

注意:要加上这句。 在这加吧。

public Form1()
{
InitializeComponent();
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
}
还是不行啊 还是会出现错误啊



你那个方法加个参数

private void StartListener(object obj)
这个参数下面要写什么东西吗


参数你可以不用,但是一定要写。

public delegate void WaitCallback(object state);

读书人网 >C#

热点推荐