Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
private void OnReceive(IAsyncResult ar)
 {

 clientSocket.EndReceive(ar);

//Convert the bytes received into an object of type Data
 Data msgReceived = new Data(byteData);

//Accordingly process the message received
 switch (msgReceived.cmdCommand)
 {

 case Command.openForm:

form1 f=new form1();
 the form is waiting here!!! \\\\\\ f.show();


break;

 }


//Start listening to receive more data from the user
 clientSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref epServer,
 new AsyncCallback(OnReceive), null);

 }
Posted
Updated 15-Oct-12 7:40am
v2
Comments
Sergey Alexandrovich Kryukov 15-Oct-12 13:41pm    
Problem is not clear; please explain what's wrong.
--SA
Sergey Alexandrovich Kryukov 15-Oct-12 13:47pm    
But after a second look, I can see a problem. Please see my answer for a fix.
--SA

1 solution

You should never call any methods/properties of the currently executing UI objects from the thread other then its associated UI thread.

Instead, you need to use the method Invoke or BeginInvoke of System.Windows.Threading.Dispatcher (for both Forms or WPF) or System.Windows.Forms.Control (Forms only).

You will find detailed explanation of how it works and code samples in my past answers:
Control.Invoke() vs. Control.BeginInvoke()[^],
Problem with Treeview Scanner And MD5[^].

See also more references on threading:
How to get a keydown event to operate on a different thread in vb.net[^],
Control events not firing after enable disable + multithreading[^].

Besides, I don't recommend using asynchronous APIs, as direct use of threading is more straightforward, simple, the logic is more linear; you got more control. Of course, you will need to use thread synchronization techniques (the less, the better, but you need to make sure your code is thread safe). But those thread synchronization techniques are always the same, while asynchronous code depends on particular APIs. I think that asynchronous APIs flourished when multithreading was not a commonplace as it is now.

—SA
 
Share this answer
 
Comments
Mehdi Gholam 15-Oct-12 14:21pm    
OP : the form which is f is still waiting and the program is stop and waiting without error !!!!!???
Sergey Alexandrovich Kryukov 15-Oct-12 14:46pm    
Thank you, Mehdi.
In such cases, it's the best to just remove a non-solution post.

@OP: please first utilize the directions I provided. The code you've written does not worth debugging; it won't work anyway.
--SA
RaisKazi 15-Oct-12 20:15pm    
My 5.
Sergey Alexandrovich Kryukov 15-Oct-12 21:19pm    
Thank you, Rais.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900