如何检查线程中是否有可用的 tcp 端口?我尝试使用后台工作线程,它工作,但更新相当缓慢。我想向我的 UI 线程报告进度。这是正确的方法吗?
BackgroundWorker authStatus = new BackgroundWorker {WorkerReportsProgress = true};
authStatus.DoWork += AuthStatusWork;
authStatus.ProgressChanged += AuthStatusProgressChanged;
public void AuthStatusWork(object sender, EventArgs e)
{
var thread = sender as BackgroundWorker;
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socket.SendTimeout = 3;
while (true)
{
try
{
socket.Connect(auth[0], Convert.ToInt32(auth[1]));
if (thread != null) thread.ReportProgress(1);
}
catch (SocketException ex)
{
if (ex.SocketErrorCode != SocketError.ConnectionRefused &&
ex.SocketErrorCode != SocketError.TimedOut) continue;
if (thread != null) thread.ReportProgress(0);
}
}
}
}
public void AuthStatusProgressChanged(object sender, ProgressChangedEventArgs e)
{
switch (e.ProgressPercentage)
{
case 0:
AuthStatus.Foreground = Brushes.Red;
AuthStatus.Content = "Offline";
break;
case 1:
AuthStatus.Foreground = Brushes.Green;
AuthStatus.Content = "Online";
break;
}
}