0

I'm using a Socket to connect to a TCP Server. However, when I try to connect, the whole program freezes. How can I make it so the program doesn't freeze but will still attempt to connect?

That's my connection code.

_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
    _socket.Connect(IP, Port);
}
Surfbutler
  • 1,529
  • 2
  • 17
  • 38

2 Answers2

0

Deriving from this question:

Thread thread = new Thread(YourMethodName);
thread.Start();

Also, check out this question to understand how to achieve the result using BackgroundWorkers.

A snippet from the related post:

BackgroundWorker bw = new BackgroundWorker();

        // this allows our worker to report progress during work
        bw.WorkerReportsProgress = true;

        // what to do in the background thread
        bw.DoWork += new DoWorkEventHandler(
        delegate(object o, DoWorkEventArgs args)
        {
            BackgroundWorker b = o as BackgroundWorker;

            // do some simple processing for 10 seconds
            for (int i = 1; i <= 10; i++)
            {
                // report the progress in percent
                b.ReportProgress(i * 10);
                Thread.Sleep(1000);
            }

        });
Community
  • 1
  • 1
TheGeekZn
  • 3,696
  • 10
  • 55
  • 91
0

You can delegate connection logic to BackgroudWorker Class. This way you can have atleast your UI thread (assuming win/WPF app) free to take input from user.

TalentTuner
  • 17,262
  • 5
  • 38
  • 63