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