我正在使用Socket连接到TCP服务器。但是,当我尝试连接时,整个程序会冻结。如何才能使程序不冻结但仍会尝试连接?
这是我的连接代码。
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
_socket.Connect(IP, Port);
}
答案 0 :(得分:0)
从this question派生:
Thread thread = new Thread(YourMethodName);
thread.Start();
另外,check out this question了解如何使用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);
}
});
答案 1 :(得分:0)
您可以将连接逻辑委派给BackgroudWorker Class。这样你就可以免费获得用户输入的至少你的UI线程(假设win / WPF应用程序)。