gpt4 book ai didi

c# - 如何独立于数据加载 UI

转载 作者:太空宇宙 更新时间:2023-11-03 17:57:57 25 4
gpt4 key购买 nike

我正在使用 C# 和网络服务器中的数据库创建一个应用程序。从网络服务器访问数据时,它非常慢,并且在加载数据之前表单也会挂起。有没有办法先加载表单,然后稍后的数据?

最佳答案

解决这个问题的常用方法是使用 BackgroundWorker类。

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
}
}

关于c# - 如何独立于数据加载 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6578342/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com