-2

I am trying to make a client-server application using some person's code for console as an example. In the Main function he uses this

Task.Run(() => { while (true) ReceivePacket(); });

for receiving packets. He sends a packet from one client and receives it with this on another. ReceivePacket is a custom function that does some things when a packet is received.

I am using WinForms and I need to catch all sent packets somehow. What if I put this line in the constructor of my main form? Will it work then? Or should I place it somewhere else?

My app is not finished yet so I can't just launch and check.

J. Doe
  • 229
  • 3
  • 15
  • can you show the full method where you are calling / defining the async method also do a google search on `Task.Run()=>` c# msdn examples – MethodMan Dec 15 '17 at 22:28
  • You can put it wherever you want, as long as you only call it once. What kind of client-server application are you building? Wont you need to be able to stop this loop again? – Malte R Dec 15 '17 at 22:29
  • @Malte R, it's a game for 2 players. And yes I think it must be stopped when one of the players wins or is disconnected. I didn't think about it. – J. Doe Dec 15 '17 at 22:44
  • 1
    But if we give you an answer, how will you know if it works? – mjwills Dec 15 '17 at 22:53
  • @mjwills If the answer is right, then it will work well after I finish, maybe. This application is my first relatively large project, and it is hard for me to plan everything that my program will contain. I write the code in the order in which I think. – J. Doe Dec 15 '17 at 23:12

1 Answers1

1

You use Task.Run for CPU bound operation and not for network call. Refer this blog from Stephen Cleary. If you need to make a network call (client-server) using Task.Run is not correct.

To talk to server, you can expose your operations on server through Web API. And on the client side (that is your web forms) call the API using HttpClient. Refer this tutorial to understand how to call a Web API from client.

mjwills
  • 23,389
  • 6
  • 40
  • 63
Ankit Vijay
  • 3,752
  • 4
  • 30
  • 53