简体   繁体   English

如何减少表单加载时间从一种形式到另一种形式

[英]How to reduce form load time from one form to another

this is the code from my menu and it creates an instance of another form when clicked. 这是我菜单中的代码,单击后会创建另一个表单的实例。

private void btn_AdminReg_Click(object sender, EventArgs e)
{
    this.Hide();
    Admin_Login login = new Admin_Login(1);
    login.Show();
}

it passes a parameter to varify which login wold it take (same login form is used to login to multiple forms) 它传递一个参数来更改需要的登录名(使用相同的登录表单登录到多个表单)

in the next form the code looks something like this ( Data is a class that i've defined.it has connection string and getting data form db and inserting, updating, deleting all of functions) 在下一种形式中,代码看起来像这样( Data是我定义的一个类。它具有连接字符串,并从db获取数据并插入,更新,删除所有功能)

public partial class Admin_Login : MetroFramework.Forms.MetroForm
{
    int separator; // this is used to separate different logins

    public Admin_Login(int value)
    {
        InitializeComponent();
        separator = value;
    }

    //------- Legend ---------
    //if separator= 1 : AdminTerminal
    //if separator= 2 : UpdatingTerminal
    //if separator= 3 : View Registration
    //if separator= 4 : Registration
    //if separator= 5 : Reports
    //if separator= 6 : Cancel Union

    static string path = Path.GetFullPath(Environment.CurrentDirectory);
    static string dataBaseName = "Trade_Union_Registration.mdf";

    private void btn_Login_Click(object sender, EventArgs e)
    {
        if (separator == 1)
        {
            Data getTable = new Data();
            DataTable table = getTable.GetData("select  UserName,Password from SuperUser where UserName='" + txt_UserName.Text + "' and Password='" + txt_Password.Text + "'");

            if (table.Rows.Count == 1)
            {
                this.Hide();
                TerminalAdmin AdminTerminal = new TerminalAdmin();
                AdminTerminal.Show();
            }
            else
            {
                MetroFramework.MetroMessageBox.Show(this, "Invalid Username/Password please check your Username and Password and try again.", "Access Denied", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txt_Password.Clear();
            }
        }
        else if (separator == 2)
        {
            Data getTable = new Data();
            DataTable table = getTable.GetData("select  UserName,Password from Admin_Table where UserName='" + txt_UserName.Text + "' and Password='" + txt_Password.Text + "'");

            if (table.Rows.Count == 1)
            {
                Data getter = new Data();
                DataTable dt = getter.GetData("select UserID from Admin_Table where UserName='" + txt_UserName.Text + "'");
                MessageBox.Show(dt.Rows[0][0].ToString());
                this.Hide();
                Updating form = new Updating(dt.Rows[0][0].ToString(), txt_UserName.Text);
                form.Show();
            }

when i run this code my form takes a lot of time to load one form to other form. 当我运行此代码时,我的表单需要花费很多时间才能将一个表单加载到其他表单。 how to solve this? 如何解决呢?

First off, I have to agree that your approaches (Connacting SQL Queries, plain passwords) are questionable for all but the most primitive learning examples. 首先,我必须同意,除了最原始的学习示例外,您的方法(联系SQL查询,纯密码)都存在疑问。 But I am going to asume it is just one such learning example. 但我想这只是一个这样的学习示例。

Nothing in the shown could should take long, but a large part of the code is missing. 所显示的内容可能不会花很长时间,但是缺少了大部分代码。 My best guess is that you are doing some Database Queries somewhere between the constructor and actually showing the Form. 我最好的猜测是,您正在构造函数与实际显示表单之间的某个位置进行一些数据库查询。 In such cases it is important to understand the "Lifecycle" of a Windows Forms Form and in what order any events are raised. 在这种情况下,重要的是要了解Windows窗体窗体的“生命周期”,以及引发什么事件的顺序。 Unfortunately, I have issues findign a listing like for asp.net pages. 不幸的是,我发现问题像asp.net页面一样。 This is the closest I could get: https://docs.microsoft.com/en-us/dotnet/framework/winforms/order-of-events-in-windows-forms 这是我能得到的最接近的东西: https : //docs.microsoft.com/zh-cn/dotnet/framework/winforms/order-of-events-in-windows-forms

If there is any code that must run after the form is first shown, put it into the Form.Shown() Event. 如果在第一次显示该表单后必须运行任何代码,请将其放入Form.Shown()事件。 That is it's purpose for existing. 那是现有的目的。

On a general note, you will need some form of Multitasking to make this kind of application work: Database Queries, Network operations and to a lesser degree Disk operations are notoriously slow (when compared with most other actions code can do). 总的来说,您需要某种形式的多任务处理才能使这种应用程序正常工作:数据库查询,网络操作以及程度较低的磁盘操作都非常缓慢(与大多数其他代码执行的操作相比)。 Any approach for Multitasking/-Threading should work: BackgroundWorker , Threads, async...await pattern. 任何用于多任务/线程处理的方法都可以使用: BackgroundWorker ,Threads,async ... await模式。

If you do not do that, you just lock up the GUI Thread. 如果不这样做,则只需锁定GUI线程即可。 Wich to the user will be "not responding" message and not reacting to any mouse actions. 会向用户发送“不响应”消息,并且不对任何鼠标操作做出反应。

I would: 我会:

  • Add one or more background workers to this form (one per DB operation). 向此表单添加一个或多个后台工作者(每个数据库操作一个)。 Pick BackgroundWorker because it is a good beginners tool for learning Multitasking/-Threading. 选择BackgroundWorker,因为它是学习多任务/线程的一个很好的初学者工具。
  • Only start the background workers in with the buttons. 仅使用按钮启动后台工作人员。 Do not put actuall DB access code behind those buttons. 不要在这些按钮后面放置实际的数据库访问代码。 If you put DB access code behinds buttons, the form can not respond until the DB access either finished or timed out. 如果将数据库访问代码放在按钮后面,则在数据库访问完成或超时之前,表单无法响应。
  • Put the results onto the screen when the BackgroundWorker finishes. BackgroundWorker完成时,将结果显示在屏幕上。 There is nothing you can do with regards to Progress reporting with a DB access. 对于具有数据库访问权限的进度报告,您无能为力。

Years ago I made a simple BackgroundWorker example. 多年前,我做了一个简单的BackgroundWorker示例。 A few stuff like the reporting has to be cut out for this, but overall it should still put you on the right track: 为此,必须删除一些诸如报告之类的内容,但总的来说,它仍然应该使您走上正轨:

 #region Primenumbers private void btnPrimStart_Click(object sender, EventArgs e) { if (!bgwPrim.IsBusy) { //Prepare ProgressBar and Textbox int temp = (int)nudPrim.Value; pgbPrim.Maximum = temp; tbPrim.Text = ""; //Start processing bgwPrim.RunWorkerAsync(temp); } } private void btnPrimCancel_Click(object sender, EventArgs e) { if (bgwPrim.IsBusy) { bgwPrim.CancelAsync(); } } private void bgwPrim_DoWork(object sender, DoWorkEventArgs e) { int highestToCheck = (int)e.Argument; //Get a reference to the BackgroundWorker running this code //for Progress Updates and Cancelation checking BackgroundWorker thisWorker = (BackgroundWorker)sender; //Create the list that stores the results and is returned by DoWork List<int> Primes = new List<int>(); //Check all uneven numbers between 1 and whatever the user choose as upper limit for(int PrimeCandidate=1; PrimeCandidate < highestToCheck; PrimeCandidate+=2) { //Report progress thisWorker.ReportProgress(PrimeCandidate); bool isNoPrime = false; //Check if the Cancelation was requested during the last loop if (thisWorker.CancellationPending) { //Tell the Backgroundworker you are canceling and exit the for-loop e.Cancel = true; break; } //Determin if this is a Prime Number for (int j = 3; j < PrimeCandidate && !isNoPrime; j += 2) { if (PrimeCandidate % j == 0) isNoPrime = true; } if (!isNoPrime) Primes.Add(PrimeCandidate); } //Tell the progress bar you are finished thisWorker.ReportProgress(highestToCheck); //Save Return Value e.Result = Primes.ToArray(); } private void bgwPrim_ProgressChanged(object sender, ProgressChangedEventArgs e) { pgbPrim.Value = e.ProgressPercentage; } private void bgwPrim_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { pgbPrim.Value = pgbPrim.Maximum; this.Refresh(); if (!e.Cancelled && e.Error == null) { //Show the Result int[] Primes = (int[])e.Result; StringBuilder sbOutput = new StringBuilder(); foreach (int Prim in Primes) { sbOutput.Append(Prim.ToString() + Environment.NewLine); } tbPrim.Text = sbOutput.ToString(); } else { tbPrim.Text = "Operation canceled by user or Exception"; } } #endregion 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM