0
我有一个问题,当我尝试通过点击“X”,这是对形式的右侧我得到它说在UDP连接获取错误
的我错误关闭应用程序/ O操作已由于线程存在或应用程序请求
而且我在这行代码得到的中止:
newsocket.EndReceiveFrom(ar,ref tmp);
这里的例子我代码:
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
int m;
Socket newsocket;
EndPoint tmp;
IPEndPoint sen = new IPEndPoint(IPAddress.Loopback, 5001);
byte[] data = new byte[1024];
byte[] buffer = new byte[1024];
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
CheckForIllegalCrossThreadCalls = false;
IPEndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1235);
newsocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,ProtocolType.Udp);
newsocket.Bind(endpoint);
tmp = (EndPoint)sen;
newsocket.BeginReceiveFrom(data, 0, 40, SocketFlags.None,ref tmp, new AsyncCallback(ReadCallback), tmp);
Thread thread = new Thread(new ThreadStart(this.threadtask));
thread.Start();
}
protected void ReadCallback(IAsyncResult ar)
{
newsocket.EndReceiveFrom(ar,ref tmp);
send();
newsocket.BeginReceiveFrom(data, 0, 40, SocketFlags.None, ref tmp, new AsyncCallback(ReadCallback), tmp);
}
private void send()
{
newsocket.BeginSendTo(buffer, 0, 7, SocketFlags.None, sen, newAsyncCallback(SendCallback), sen);
}
protected void SendCallback(IAsyncResult ar)
{
newsocket.EndSendTo(ar);
}
private void threadtask()
{
while (true)
{
cMicroLCCore.getDAC(m).Value = data[m];
}
}
}
}
@ Germann:谢谢你的回答,但我在编程方面很活跃,可以请你告诉我怎样才能做到这一点。 – user1465977 2012-08-17 08:56:05
将'Thread thread;'定义为一个类变量。 定义'form_unload()'处理程序并在卸载处理程序中运行 'thread.Stop();'。 – 2012-08-17 10:05:48
你好,我已经尝试过,但没有发生.. – user1465977 2012-08-17 11:48:47