我怎么知道任务是否完成 [英] how can I know if a task is completed

查看:50
本文介绍了我怎么知道任务是否完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网格,当选择负载大量的一行信息 - 7个网格和DevExpress的报告需要加载,这需要大量的时间

I have a grid that loads lots of information when a row is selected - 7 more grids and a DevExpress report need to load, and it takes a lot of time

我将所有方法都放在任务中以加快流程.

I put all the methods into tasks to speed up the process.

但是,如果在上一行完成加载之前选择了另一行,则会导致错误.

But if another row is selected before the previous one finishes loading, it causes errors.

我想知道如何检查任务是否完成以及在再次加载新数据之前等待还是取消任务.(我是异步编程的新手)

I would like to know how to check if the task is finished and the either wait or cancel the task before loading again with new data. (I am new to asynchronous programming)

这是我的任务的一个示例(其中有8个,每个任务一个接一个):

This is an example of my tasks (there are 8 of them, each called one after another):

    private async void LoadSSNs()
    {
        await Task.Run(() => grdSSNs.DataSource = ICTBLL.GetData(ID));
    }

如何将其更改为可以检查是否完成的Task对象?

How can I change it into a Task object that I can check if complete?

推荐答案

您几乎永远都不应使用async/await的 void 返回类型(有例外,但从此开始).您的方法需要返回 Task ,这样您就可以等待或检查完成状态了.

You should almost never have a void return type with async/await (there are exceptions, but start with that). Your method needs to return a Task so you have something to wait on or check for completion status.

private async Task LoadSSNs()
{
    await Task.Run(() => grdSSNs.DataSource = ICTBLL.GetData(ID));
}

如何确定任务是否完成取决于您需要执行的操作.如果您需要在任务异步运行时做一些工作,可以这样做:

How you determine if the task is complete depends on what you need to do. If you need to do some work while the task runs asynchronously, you could do this:

var t = LoadSSNs();

// do something while task is running.

t.Wait(); // this is one option.
if (t.Status == TaskStatus.Faulted) { } // handle problems from task.

如果任务完成时您还有更多工作要做,则可以执行以下操作:

If you have more work to do while the task completes, you could do something like this:

while(!t.IsCompleted)
{
    // do some other work.
}

同样,该任务由您自己决定;重要的部分是您需要从异步方法中返回等待的 Task .

Again, what you do with the task is up to you; the important part is you need to return an awaitable Task from your async method.

这篇关于我怎么知道任务是否完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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