如何异步填充 ObjectListView 中的字段

问题描述 投票:0回答:1

我正在使用 ObjectListView 并尝试找出如何正确异步填充字段/列数据。

ObjectListView 使用“AspectSetter”的概念,它允许您提供行字段数据的内容,如下所示:

tlist.GetColumn(0).AspectGetter = delegate(Person x) { return x.Name; };

就我而言,我返回的字段需要一些时间来计算:

tlist.GetColumn(0).AspectGetter = delegate(Person x) { return SomeCalculation(); };

在不阻塞 UI 的情况下返回字段数据并允许填充其余字段数据的最佳方法是什么?

c# .net objectlistview
1个回答
0
投票

创建一个

async
方法来执行计算并返回结果。

private async Task<string> CalculateAsync(Person person)
{
    // Simulate a delay, replace with your actual asynchronous operation.
    await Task.Delay(TimeSpan.FromSeconds(2));

    // Perform your actual calculation here.
    string result = "Result";

    return result;
}


tlist.GetColumn(0).AspectGetter = delegate(Person x)
{
    // Use Task.Run to run the async method on a background thread.
    return Task.Run(async () =>
    {
        string result = await CalculateAsync(x);

        // Use Invoke to update the UI on the main thread.
        tlist.Invoke((Action)(() =>
        {
            tlist.RefreshObject(x);
        }));

        return result;
    });
};

在上面的代码中,计算是在后台线程上执行的,防止它阻塞 UI,并且当计算完成时,

ObjectListView
会使用 UI 线程上的结果进行更新。

© www.soinside.com 2019 - 2024. All rights reserved.