首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >优化加载页面

优化加载页面
EN

Stack Overflow用户
提问于 2019-07-29 16:49:09
回答 1查看 68关注 0票数 0

所以我正在处理WPF中的问题。

我有一个页面,当你点击RichTextBox作为输出数据框的按钮时加载。

问题是,它检查文件是否可以在FTP上访问,但它首先进行检查,所以需要一段时间,然后显示带有输出的页面。

我想首先显示页面与输出框,然后它将开始显示数据(就像你在安装程序等)。

这是页面本身的代码:

代码语言:javascript
复制
public partial class ArtaActionsPage : Page
{
    public ArtaActionsPage()
    {
        InitializeComponent();
        Loaded += OnLoaded;
    }

    private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
    {
        AddBlackLine("");
        AddBlackLine("Checking if everything is ready...");
        AddBlackLine("");

        bool AdobeReady = false;
        bool SevenZipReady = false;
        bool JavaReady = false;
        bool EsetReady = false;

        if (Global_Action_Variables.Arta_Variables.ArtaAdobeSwitch == true)
        {
            AddBlackLine("Checking for Adobe installator...");
            bool CheckForAdobe = General_Functions.CheckIfFileExistsOnFTP("Ultra_Script/Basic_SW/Adobe_Reader.exe");
            if(CheckForAdobe == true)
            {
                AddGreenLine("Installer for Adobe accesible.");
                AdobeReady = true;
            }
            else
            {
                AddRedLine("Installer not accesible on FTP!!! Canceling job...");
                AddRedLine("Check FTP repozitary if file in Ultra_Script/Basic_SW/Adobe_Reader.exe exists and ftp account have enough rights for this file.");
            }
        }

        if (Global_Action_Variables.Arta_Variables.ArtaSevenZip == true)
        {
            AddBlackLine("");
            AddBlackLine("");
            AddBlackLine("Checking for SevenZip installer...");
            bool CheckForSevenZip = General_Functions.CheckIfFileExistsOnFTP("Ultra_Script/Basic_SW/7zip.exe");
            if(CheckForSevenZip == true)
            {
                AddGreenLine("Installer for 7zip accesible.");
                SevenZipReady = true;
            }
            else
            {
                AddRedLine("Installer not accesible on FTP!!! Canceling job...");
                AddRedLine("Check FTP repozitary if file in Ultra_Script/Basic_SW/7zip.exe exists and ftp account have enough rights for this file.");
            }
        }

        if(Global_Action_Variables.Arta_Variables.ArtaJava == true)
        {
            AddBlackLine("");
            AddBlackLine("");
            AddBlackLine("Checking for Java installer...");
            bool CheckForJava = General_Functions.CheckIfFileExistsOnFTP("Ultra_Script/Basic_SW/JaVa.exe");
            if(CheckForJava == true)
            {
                AddGreenLine("Installer for Java accesible");
                JavaReady = true;
            }
            else
            {
                AddRedLine("Installer not accesible on FTP!!! Canceling job...");
                AddRedLine("Check FTP repozitary if file in Ultra_Script/Basic_SW/JaVa.exe exists and ftp account have enough rights for this file.");
            }
        }

        if(Global_Action_Variables.Arta_Variables.ArtaEset == true)
        {
            AddBlackLine("");
            AddBlackLine("");
            AddBlackLine("Checking for Arta ESET installer...");
            bool CheckForArtaEset = General_Functions.CheckIfFileExistsOnFTP("Ultra_Script/Basic_SW/Arta/ERA_ESET.exe");
            if(CheckForArtaEset == true)
            {
                AddGreenLine("Installer for ESET accesible");
                EsetReady = true;
            }
            else
            {
                AddRedLine("Installer not accesible on FTP!!! Canceling job...");
                AddRedLine("Check FTP repozitary if file in UUltra_Script/Basic_SW/Arta/ERA_ESET.exe exists and ftp account have enough rights for this file.");
            }
        }

        if(AdobeReady == true)
        {
            AddBlackLine("");
            AddBlackLine("");
            AddBlackLine("Test");
            General_Functions.DownloadFileFromFTP("Ultra_Script/Basic_SW/Adobe_Reader.exe", "Adobe_Reader.exe");
        }
        else
        {
            AddBlackLine("");
            AddRedLine("Failed.");
        }
    }

    private void AddRedLine(string text)
    {
        TextRange tr = new TextRange(outputBox.Document.ContentEnd, outputBox.Document.ContentEnd);
        tr.Text = text;
        tr.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red);
        outputBox.AppendText("\r");
        outputBox.ScrollToEnd();
    }

    private void AddGreenLine(string text)
    {
        TextRange tr = new TextRange(outputBox.Document.ContentEnd, outputBox.Document.ContentEnd);
        tr.Text = text;
        tr.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Green);
        outputBox.ScrollToEnd();
    }

    private void AddBlackLine(string text)
    {
        TextRange tr = new TextRange(outputBox.Document.ContentEnd, outputBox.Document.ContentEnd);
        tr.Text = text;
        tr.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Black);
        outputBox.AppendText("\r");
        outputBox.ScrollToEnd();
    }
}    

这是显示新页面的按钮的代码:

代码语言:javascript
复制
private void ArtaDoITButton_Click(object sender, RoutedEventArgs e)
{
    if (File.Exists("settings.xml"))
    {
        XmlSerializer xs = new XmlSerializer(typeof(Information));
        FileStream read = new FileStream("settings.xml", FileMode.Open, FileAccess.Read, FileShare.Read);
        Information info = (Information)xs.Deserialize(read);

        try
        {
            string a = info.FtpPassword;
            string FTPPassword = EncryDecryptor.Decrypt(a);
            bool TestFTP = General_Functions.isValidConnection(info.HDSynologyIP, info.FtpUsername, FTPPassword);
            if(TestFTP == true)
            {
                ArtaActionsFrame.Content = new ArtaActionsPage();
            }
            else
            {
                MessageBox.Show("Failed login to FTP repozitary. Check your credentials in settings.");
            }
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.ToString());
            read.Close();
        }
        read.Close();
    }
    else
    {
        MessageBox.Show("Chybí settings file!!");
    }
}     

页面的初始化:

代码语言:javascript
复制
public ArtaActionsPage()
{
    InitializeComponent();
    Loaded += OnLoaded;
}   

有谁知道如何优化它,这样它就不会在加载页面之前进行检查?

谢谢你所有的回答。

EN

回答 1

Stack Overflow用户

发布于 2019-07-29 17:29:26

您必须使用async/await异步初始化Page。所有的初始化过程都应该移到一个公共InitalizeAsync()方法的ArtaActionsPage中:

加载页面事件处理程序:

代码语言:javascript
复制
private async void ArtaDoITButton_Click(object sender, RoutedEventArgs e)
{
  if (!File.Exists("settings.xml"))
  {
    MessageBox.Show("Chybí settings file!!");
    return;
  }

  var nextPage = new ArtaActionsPage();

  // Show the page immediately
  ArtaActionsFrame.Content = nextPage;

  if (!await nextPage.TryInitializeAsync())
  {
    MessageBox.Show("Failed login to FTP repozitary. Check your credentials in settings.");

    // Show previous page again
  }
}

Page.xaml.cs:

代码语言:javascript
复制
private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
{}

public async Task<bool> TryInitializeAsync()
{
  bool ftpIsValid = await ValidateFtpAsync();
  if (!ftpIsValid)
  {        
    return false;
  }

  await CheckIfFileExistsOnFTPAsync();
  return true;
}

private async Task<bool> ValidateFtpAsync()
{
  return await Task.Run(
    () =>
    {
      var xs = new XmlSerializer(typeof(Information));
      using (var read = new FileStream("settings.xml", FileMode.Open, FileAccess.Read, FileShare.Read))
      {
        Information info = (Information) xs.Deserialize(read);

        try
        {
          string a = info.FtpPassword;
          string fTPPassword = EncryDecryptor.Decrypt(a);
          return General_Functions.isValidConnection(info.HDSynologyIP, info.FtpUsername, FTPPassword);
        }
        catch (Exception ex)
        {
          MessageBox.Show(ex.ToString());
        }
      }

      return false;
    });
}

public async Task CheckIfFileExistsOnFTPAsync()
{
  bool ftpIsValid = await ValidateFtpAsync();
  if (!ftpIsValid)
  {        
    return false;
  }

  await Task.Run(
    () =>
    {
      AddBlackLine("");
      AddBlackLine("Checking if everything is ready...");
      AddBlackLine("");

      bool AdobeReady = false;
      bool SevenZipReady = false;
      bool JavaReady = false;
      bool EsetReady = false;

      if (Global_Action_Variables.Arta_Variables.ArtaAdobeSwitch == true)
      {
        AddBlackLine("Checking for Adobe installator...");
        bool CheckForAdobe = General_Functions.CheckIfFileExistsOnFTP("Ultra_Script/Basic_SW/Adobe_Reader.exe");
        if (CheckForAdobe == true)
        {
          AddGreenLine("Installer for Adobe accesible.");
          AdobeReady = true;
        }
        else
        {
          AddRedLine("Installer not accesible on FTP!!! Canceling job...");
          AddRedLine(
            "Check FTP repozitary if file in Ultra_Script/Basic_SW/Adobe_Reader.exe exists and ftp account have enough rights for this file.");
        }
      }

      if (Global_Action_Variables.Arta_Variables.ArtaSevenZip == true)
      {
        AddBlackLine("");
        AddBlackLine("");
        AddBlackLine("Checking for SevenZip installer...");
        bool CheckForSevenZip = General_Functions.CheckIfFileExistsOnFTP("Ultra_Script/Basic_SW/7zip.exe");
        if (CheckForSevenZip == true)
        {
          AddGreenLine("Installer for 7zip accesible.");
          SevenZipReady = true;
        }
        else
        {
          AddRedLine("Installer not accesible on FTP!!! Canceling job...");
          AddRedLine(
            "Check FTP repozitary if file in Ultra_Script/Basic_SW/7zip.exe exists and ftp account have enough rights for this file.");
        }
      }

      if (Global_Action_Variables.Arta_Variables.ArtaJava == true)
      {
        AddBlackLine("");
        AddBlackLine("");
        AddBlackLine("Checking for Java installer...");
        bool CheckForJava = General_Functions.CheckIfFileExistsOnFTP("Ultra_Script/Basic_SW/JaVa.exe");
        if (CheckForJava == true)
        {
          AddGreenLine("Installer for Java accesible");
          JavaReady = true;
        }
        else
        {
          AddRedLine("Installer not accesible on FTP!!! Canceling job...");
          AddRedLine(
            "Check FTP repozitary if file in Ultra_Script/Basic_SW/JaVa.exe exists and ftp account have enough rights for this file.");
        }
      }

      if (Global_Action_Variables.Arta_Variables.ArtaEset == true)
      {
        AddBlackLine("");
        AddBlackLine("");
        AddBlackLine("Checking for Arta ESET installer...");
        bool CheckForArtaEset = General_Functions.CheckIfFileExistsOnFTP("Ultra_Script/Basic_SW/Arta/ERA_ESET.exe");
        if (CheckForArtaEset == true)
        {
          AddGreenLine("Installer for ESET accesible");
          EsetReady = true;
        }
        else
        {
          AddRedLine("Installer not accesible on FTP!!! Canceling job...");
          AddRedLine(
            "Check FTP repozitary if file in UUltra_Script/Basic_SW/Arta/ERA_ESET.exe exists and ftp account have enough rights for this file.");
        }
      }

      if (AdobeReady == true)
      {
        AddBlackLine("");
        AddBlackLine("");
        AddBlackLine("Test");
        General_Functions.DownloadFileFromFTP("Ultra_Script/Basic_SW/Adobe_Reader.exe", "Adobe_Reader.exe");
      }
      else
      {
        AddBlackLine("");
        AddRedLine("Failed.");
      }
    });
}

还要考虑将General_Functions.CheckIfFileExistsOnFTP()转换为async方法。

现在,ArtaActionsPage立即显示出来。无论初始化是否失败,InitializeAsync都会返回bool。如果失败了,您可以处理这种情况,例如,显示您的消息,然后导航回上一页。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57250210

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档