【发布时间】:2014-04-19 17:27:09
【问题描述】:
我有一个耗时的任务来测试几个网络连接。在下面的示例中,我将其限制为一个连接。 通常连接会很快返回,但可能会发生无法建立连接的情况,从而导致套接字超时。在此期间,我想在表单中显示一个“闲置”gif,当连接成功时,应用程序应该将表单中的图像更改为一些 绿色检查图标或在连接失败的情况下应显示红色图标“停止器”。
不知何故,我无法让闲置 gif 变得可见和动画。要模拟失败的连接,可以输入无效的端口号或不存在的地址。
任何线索我错过了什么或做错了什么?
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
///
#region BackgroundWorker
private System.ComponentModel.BackgroundWorker backgroundWorker = new System.ComponentModel.BackgroundWorker();
private delegate void SomeLongRunningMethodHandler(object sender, EventArgs e);
#endregion
private System.ComponentModel.IContainer components = null;
Button button,button2;
static Socket socket;
static bool success;
private static bool done;
private Label lbl1;
private Label lbl2;
private TextBox address;
private TextBox port;
private PictureBox p;
private static String port_number,host;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
private void RunTest(object o,EventArgs e)
{
p.Visible = true;
SomeLongRunningMethodHandler synchronousFunctionHandler =
default(SomeLongRunningMethodHandler);
synchronousFunctionHandler =
TestConnection;
synchronousFunctionHandler.Invoke(o, e);
}
private void TestConnection(object o, EventArgs e)
{
host = address.Text;
port_number = port.Text;
if (null != socket)
{
socket.Close();
}
Thread.Sleep(1000);
IPEndPoint myEndpoint = new IPEndPoint(0, 0);
IPHostEntry remoteMachineInfo = Dns.GetHostEntry(host);
IPEndPoint serverEndpoint = new IPEndPoint(remoteMachineInfo.AddressList[0],
int.Parse(port_number));
socket = new Socket(myEndpoint.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try
{
socket.Connect(serverEndpoint);
success = true;
p.Image = global::BlockingUI.Properties.Resources.accept;
}
catch
{
success = false;
p.Image = global::BlockingUI.Properties.Resources.stopper;
}
done = true;
}
private void ExitApp(object o, EventArgs e)
{
Application.Exit();
}
}
【问题讨论】:
-
我看到你实例化了一个
BackgroundWorker,但你从不使用它。
标签: c# multithreading user-interface backgroundworker invoke