Urgent. Socket.BeginConnect doesn't work when is called from a separatedthread

A

Anibal Acosta

One complete day a lost finding the problem, Now I know what is, but I
don't know why?

This is my simple source code. The first method call the BeginConnect()
using the same windows form thread, and the second method call the
BeginConnect() using another thread

You will think... "Why you want to execute the BeginConnect using
another thread" But believe me that a really need


I really need your help

AA




private void btnSync_Click(object sender, System.EventArgs e)
{
//When click this button, the BeginConnect method is called
//using the same thread, using this way the socket tries to
//connect and the print in the console (false)

BeginConnect();
}



private void btnAsync_Click(object sender, System.EventArgs e)
{
//When click this button, the BeginConnect method is called
//using other thread, using this way the socket tries to
//connect but print (true) in the console :(

System.Threading.Thread myThread = new System.Threading.Thread(new
System.Threading.ThreadStart(BeginConnect));
myThread.Start();
}





internal void BeginConnect()
{
Socket mSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);

IPEndPoint mEndPoint = new IPEndPoint(IPAddress.Parse("10.0.0.0"), 8978);
mSocket.BeginConnect(mEndPoint, new AsyncCallback(ConnectCallBack),
mSocket);
}


private void ConnectCallBack(IAsyncResult ar)
{
Socket mSocket = (ar.AsyncState as Socket);
Console.WriteLine(mSocket.Connected);
}
 
R

recoil

I am not sure but I think what you are doing is very wrong. Windows
does not like somebody accessing a control from another thread.
Threfore if another thread must access a control that does not belong
to it then it must Invoke it from the control's thread.

This same theory applies to .NET Controls/Forms and I believe it
applies here. In .NET 2.0 it has gotten even stricter by throwing a
specific exception anytime such touching is done.
 
A

Anibal Acosta

Yes I know that could be very wrong, but I must use because in my server the
connection can be initially by any thread.

Any way, I am looking to change the behavior

Thanks a lot

AA
 
F

Feroze [msft]

I am not understanding what the exact nature of your problem is. Is it that
you cannot access the Winform "Form" object from the thread that you
created?

Or is it that you are unable to connect?

If #1, then that is by design. If you want to access the Window from another
thread, you need to do ( m_Window.BeginInvoke(...)).

If #2, Myou are doing this already, but I didnt see it in your code
snippet - but did you do a m_Socket.,EndConnect(asyncResult) ?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top