如何加载独立于数据的 UI [英] How To Load UI Independent Of Data

查看:24
本文介绍了如何加载独立于数据的 UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用网络服务器中的 c# 和数据库创建一个应用程序.从网络服务器访问数据时,速度非常慢,而且表格也被挂起,直到数据加载完毕.有没有办法先加载表格,然后后面的数据?

I am creating an application using c# and database in webserver.while accessing data from the webserver ,it is very slow and the form is also gets hanged up until the datas are loaded.Is there a way to load the form first and the datas later ?

推荐答案

解决此问题的常用方法是使用 BackgroundWorker 类.

The common way to solve this is to use the BackgroundWorker class.

public void InitBackgroundWorker()
{
    backgroundWorker.DoWork += YourLongRunningMethod;
    backgroundWorker.RunWorkerCompleted += UpdateTheWholeUi;

    backgroundWorker.WorkerSupportsCancellation = true; // optional

    // these are also optional
    backgroundWorker.WorkerReportsProgress = true;
    backgroundWorker.ProgressChanged += UpdateProgressBar;
}

// This could be in a button click, or simply on form load
if (!backgroundWorker.IsBusy)
{
    backgroundWorker.RunWorkerAsync(); // Start doing work on background thread
}

// ...

private void YourLongRunningMethod(object sender, DoWorkEventArgs e)
{
    var worker = sender as BackgroundWorker;

    if(worker != null)
    {
        // Do work here...
        // possibly in a loop (easier to do checks below if you do)

        // Optionally check (while doing work):
        if (worker.CancellationPending == true)
        {
            e.Cancel = true;
            break; // If you were in a loop, you could break out of it here...
        }
        else
        {
            // Optionally update
            worker.ReportProgress(somePercentageAsInt);
        }

        e.Result = resultFromCalculations; // Supports any object type...
    }
}

private void UpdateProgressBar(object sender, ProgressChangedEventArgs e)
{
    int percent = e.ProgressPercentage;
    // Todo: Update UI
}

private void UpdateTheWholeUi(object sender, RunWorkerCompletedEventArgs e)
{
    if (e.Cancelled)
    {
        // Todo: Update UI
    }
    else if (e.Error != null)
    {
        string errorMessage = e.Error.Message;
        // Todo: Update UI
    }
    else
    {
        object result = e.Result;
        // Todo: Cast the result to the correct object type,
        //       and update the UI
    }
}

这篇关于如何加载独立于数据的 UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆