在我的应用中,我正在尝试使用简单的下载指示器。
class Program
{
static void Main()
{
ConsoleSpinner spin = new ConsoleSpinner();
spin.Start();
DownloadFile();
spin.Stop();
Console.ReadKey();
Environment.Exit(0);
}
private static void DownloadFile()
{
Uri url = new Uri("https://website.com");
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
try
{
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
using (Stream file = File.OpenWrite(@"C:test.txt"))
using (Stream input = response.GetResponseStream())
{
input.CopyTo(file);
}
}
}
catch (Exception ex)
{
throw;
}
}
}
任何帮助都将不胜感激。
更新
这是我要的解决方案。
class Program
{
private static BackgroundWorker worker = new BackgroundWorker();
static void Main()
{
worker.DoWork += worker_DoWork;
worker.WorkerSupportsCancellation = true;
Console.Write("Downloading ");
worker.RunWorkerAsync();
DownloadFile();
worker.Cancel.Async();
Console.ReadKey();
Environment.Exit(0);
}
private static void DownloadFile()
{
Uri url = new Uri("https://website.com");
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
try
{
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
string savePath = @"C:downloadtest.txt";
using (Stream file = File.OpenWrite(savePath))
using (Stream input = response.GetResponseStream())
{
input.CopyTo(file);
}
}
}
catch (Exception ex)
{
throw;
}
}
static void worker_DoWork(object sender, DoWorkEventArgs e)
{
int i = 0;
while (true)
{
if (worker.CancellationPending) break;
i++;
Console.CursorVisible = false;
switch (i % 4)
{
case 0: Console.Write("|"); break;
case 1: Console.Write("/"); break;
case 2: Console.Write("-"); break;
case 3: Console.Write("\"); break;
}
Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
Thread.Sleep(200);
}
}
}
更新#2
完成解决方案。
您是否尝试过使用任务使下载文件函数调用?https://msdn.microsoft.com/en-us/library/hh195051(v = vs.110(.aspx