[英]How can i make that my splash screen will start and finish according to the file downloading time?
在我的form1构造函数中,我有:
while (splash_flag == true)
{
splash.Show();
Thread.Sleep(3000);
splash_flag = false;
}
if (splash_flag == false)
{
splash.Close();
}
fileDownloadRadar(remote_image_on_server,combinedTemp);
这是fileDownloadRadar方法:
HttpWebRequest request;
void fileDownloadRadar(string uri, string fileName)
{
request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
request.CookieContainer = new CookieContainer();
request.AllowAutoRedirect = true;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.ContentType == "")
{
Logger.Write("ContentType is Empty download was not fine !!!!!");
}
if ((response.StatusCode == HttpStatusCode.OK ||
response.StatusCode == HttpStatusCode.Moved ||
response.StatusCode == HttpStatusCode.Redirect) &&
response.ContentType.StartsWith("image", StringComparison.OrdinalIgnoreCase))
{
Logger.Write("ContentType is not empty meaning download is fine");
using (Stream inputStream = response.GetResponseStream())
using (Stream outputStream = File.OpenWrite(fileName))
{
byte[] buffer = new byte[4096];
int bytesRead;
do
{
bytesRead = inputStream.Read(buffer, 0, buffer.Length);
outputStream.Write(buffer, 0, bytesRead);
} while (bytesRead != 0);
}
FinishWebRequest();
}
else
{
timer1.Stop();
timer3.Start();
}
}
现在,启动屏幕的工作方式将关闭,等待3秒钟,然后加载表单。
但是我希望启动屏幕将在下载文件开始时启动,并在下载完成然后要加载的表单时关闭。
方法FinishWebRequest是文件下载的位置。 喜欢完成下载。
我的问题是如何计算时间或如何使启动屏幕从文件下载开始并在完成时关闭?
初始屏幕和下载将必须在不同的线程中运行。 您可以创建一个新线程,也可以切换到使用异步下载方法。
无论哪种方式,我都将使用AutoResetEvent而不是splash_flag
布尔值(它可以保留我猜的名称)。 它将在复位状态下开始。 FinishWebRequest()
方法将调用splash_flag.Set()
(或您决定命名的任何名称)。 这将触发启动屏幕关闭。 您将用以下类似的简单内容替换while循环:
splash.Show();
splash_flag.WaitOne();
splash.Close();
splash_flag.WaitOne()
将挂起,直到FinishWebRequest()
调用splash_flag.Set()
为止。
编辑:由于您的启动画面必须进行动画处理。 您只需要轮询完成即可。 UI线程中存在循环将导致表单无响应。
您可以创建一个计时器来执行轮询:
splash.Show();
// Poll every 100ms. Change as desired.
var timer = new System.Timers.Timer(100) { AutoReset = true };
timer.Elapsed += (s, e) =>
{
if (splash_flag.WaitOne(0)) // Check for signal and return without blocking
{
// Use Invoke() so you only deal with the form in the UI thread
splash.Invoke(new Action(() => { splash.Close(); }));
timer.Stop();
}
}
timer.Start();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.