0

我正在使用 Socket 连接到 TCP 服务器。但是,当我尝试连接时,整个程序会冻结。我怎样才能使程序不会冻结但仍会尝试连接?

这是我的连接代码。

_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
    _socket.Connect(IP, Port);
}
4

2 回答 2

0

源自这个问题

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

另外,请查看此问题以了解如何使用BackgroundWorkers.

相关帖子的片段:

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);
            }

        });
于 2013-09-23T12:44:01.403 回答
0

您可以将连接逻辑委托给BackgroudWorker类。这样,您至少可以让您的 UI 线程(假设是 win/WPF 应用程序)自由地接受用户的输入。

于 2013-09-23T12:45:45.480 回答