Reputation: 543
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)
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));
}
How can I change it into a Task object that I can check if complete?
Upvotes: 2
Views: 38146
Reputation: 35318
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.
}
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.
Upvotes: 9