I'm using threads in c++ visualstudio2008, when my form closes the thread still stays active so I tried thread::abort when form is closing, but after calling about the thread is still alive. so I put am excption handler in the thread and when an abort exception arrive the thread exit, but the thread does not enter in the exception handler. how can I close my thread? oThread is a global object Thread.
private: void ThreadMethod(/*Object^ state*/)
{
try{
SOCKET server;
WSADATA wsaData;
sockaddr_in local;
int wsaret=WSAStartup(0x101,&wsaData);
if(wsaret!=0)
{
return;
}
local.sin_family=AF_INET;
local.sin_addr.S_un.S_addr=INADDR_ANY;
local.sin_port=htons((u_short)20248);
server=socket(AF_INET,SOCK_STREAM,0);
if(server==INVALID_SOCKET)
{
return;
}
if(bind(server,(sockaddr*)&local,sizeof(local))!=0)
{
return;
}
if(listen(server,10)!=0)
{
return;
}
SOCKET client;
sockaddr_in from;
int fromlen=sizeof(from);
int buffer;
char buff;
//this->Invoke(gcnew MethodInvoker(this, &Form1::UpdateButton));
while(!stop)
{
client=accept(server,(struct sockaddr*)&from,&fromlen);
//con la struct
int numByte=recv(client,(char*) &mystruct, (int) sizeof(mystruct), 0);
this->Invoke(gcnew MethodInvoker(this, &Form1::UpdateButton));
MessageBox::Show(mystruct.num.ToString());
closesocket(client);
}
closesocket(server);
WSACleanup();
}
catch (ThreadAbortException^ e)
{
ExitThread(0);
}
ExitThread(0);
}
private: System::Void Form1_FormClosing(System::Object^ sender, System::Windows::Forms::FormClosingEventArgs^ e) {
oThread->Abort();
if(oThread->IsAlive)
{
MessageBox::Show("ok");
}
}
};
}
How about something like this: