我编写了一个小型控制台应用程序,它与远程站点连接,下载一些数据并进行处理。因为它是网络操作,所以我希望我的应用程序足够智能,以便在没有互联网连接时进入暂停状态。如果互联网连接可用,它应该恢复工作。
到目前为止,我所做的是,如果我运行应用程序,它就会开始从远程站点下载数据。如果我断开互联网连接,它会通过显示适当的信息来正确运行。但是一旦网络连接起来,它就会恢复并且只下载一次while循环迭代的数据。
这是代码:
class Program
{
static bool networkIsAvailable = false;
static StreamWriter writer = null;
static int i = 1;
static string URI = "http://xxxxxxxxxxxxxxxxxxxxxxxxxxx/" + i + "/";
static void Main(string[] args)
{
writer = new StreamWriter("c:\\StudentsList.txt", true);
NetworkChange.NetworkAvailabilityChanged += new NetworkAvailabilityChangedEventHandler(NetworkChange_NetworkAvailabilityChanged);
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface nic in nics)
{
if (
(nic.NetworkInterfaceType != NetworkInterfaceType.Loopback && nic.NetworkInterfaceType != NetworkInterfaceType.Tunnel) &&
nic.OperationalStatus == OperationalStatus.Up)
{
networkIsAvailable = true;
}
}
if (!networkIsAvailable)
Console.WriteLine("Internet connection not available! We resume as soon as network is available...");
else
ConnectToPUServer();
}
public static void ConnectToPUServer()
{
var client = new WebClient();
while (i < 500 && networkIsAvailable)
{
string html = client.DownloadString(URI);
//some data processing
Console.WriteLine(i);
i++;
URI = "http://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/" + i + "/";
}
}
static void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
{
networkIsAvailable = e.IsAvailable;
if (!networkIsAvailable)
Console.WriteLine("Internet connection not available! We resume as soon as network is available...");
while (!networkIsAvailable)
{
//waiting for internet connection
}
ConnectToPUServer();
Console.WriteLine("Complete.");
writer.Close();
}
}
恢复后,为什么while循环ConnectToPUServer
只执行一次??
谢谢。