gpt4 book ai didi

c# - 使用异步等待方法填充数据网格

转载 作者:行者123 更新时间:2023-12-05 03:04:07 25 4
gpt4 key购买 nike

我的英语不是很好很抱歉,但我尽量完美地讲述我的问题

这是我用来加载数据网格的东西

private Task Loading(Func<string> SearchStringForUser)
{

return Task.Run(() =>
{

var query = database.Database.SqlQuery<VW_Users>("select * From VW_Users where 1 = 1 And GymID = " + PublicVar.ID + " " + SearchStringForUser());
var user = query.ToList();
Dispatcher.InvokeAsync(() =>
{
DataGrid_User.ItemsSource = user;
});
});
}

首先我有一个 InvokeAsync 但它不能完美地工作我的意思是当加载的数据要列出时我的程序挂起。无论如何,这不是我的主要问题,但如果有人知道原因是什么,可以指出它 但我的主要问题是当我有 +200 行时。程序在 30 秒或更长时间内不会加载所有日期。看起来我的程序数据网格有 30 秒或更长时间是空的。

我想按 10 行 10 行加载数据,我的意思是我想在加载 10 行时填充我的数据网格,在接下来的 10 行之后,喜欢10203040....有了这个我的数据网格将永远不会为空数据加载缓慢有人可以告诉我最好的方法吗?

最佳答案

您应该在后台线程上调用数据库,但设置 ItemsSource UI 线程上的属性。所以你的 Task应该返回 IEnumerable<User>但不要碰 DataGrid .然后您可以等待 Task .

只要 Loading 就可以了从 UI 线程调用方法:

private async Task Loading(Func<string> SearchStringForUser)
{
var user = await Task.Run(() =>
{
var query = database.Database.SqlQuery<VW_Users>("select * From VW_Users where 1 = 1 And GymID = " + PublicVar.ID + " " + SearchStringForUser());
return query.ToList();
});
DataGrid_User.ItemsSource = user;
}

但是由于查询一次返回所有行,所以没有“加载 10 行时”。你一次得到它们。如果你不想要这个,你需要使用某种数据阅读器来一条一条地读取记录。你可以创建一个 ObservableCollection并按时间间隔填充这个。这是一个应该给你想法的例子:

ObservableCollection<VW_Users> collection = new ObservableCollection<VW_Users>();
object @lock = new object();
BindingOperations.EnableCollectionSynchronization(collection, @lock);
DataGrid_User.ItemsSource = collection;

Task.Run(() =>
{
using (SqlConnection connection = new SqlConnection("connection string...."))
{
SqlCommand command = new SqlCommand("select * From VW_Users where GymID = @GymId", connection);
command.Parameters.AddWithValue("GymId", PublicVar.ID + " " + SearchStringForUser());
connection.Open();

SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
const int N = 10;
VW_Users[] cache = new VW_Users[N];
int counter = 0;
while (reader.Read())
{
VW_Users obj = new VW_Users();
obj.Property1 = Convert.ToString(reader["Column1"]);
cache[counter] = obj;
//...and so on for each property...

if (++counter == N)
{
//add N items to the source collection
foreach (VW_Users x in cache) collection.Add(x);
counter = 0;
//add a delay so you actually have a chance to see that N items are added at a time
System.Threading.Thread.Sleep(1000);
}
}
//add any remaining items
for (int i = 0; i<counter; ++i) collection.Add(cache[i]);
}
reader.Close();
}
});

关于c# - 使用异步等待方法填充数据网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53151080/

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