简体   繁体   中英

How to identify task when reporting progress after launching multiple tasks

I use Progress to report Task action in a Winforms application. I am not sure how to report the task identity so that the UI can act accordingly, ie, add item to tab page 1 if task 1 returned a result, and add item to tab page 2, if task 2 returned a result.

I am using a foreach loop to create tasks, which all do the same thing. I need task identity based on the order when the task was created, ie, when first task is created, the UI knows it's "task 1" that reports back information, and so on. The number of tasks is created based on the number of the loop, which may change.

At first I thought Task.Id can be used to identify the task. But according to MSDN , Task IDs are assigned on-demand and do not necessarily represent the order in which task instances are created. And task identifiers are not guaranteed to be unique.

I use Progress as indicated in this tutorial .

I essentially increase an count within the loop. Pass that count to each task I created and report back the number to UI. Here is the step:

First, I pass the count into the tasks:

//Create the taskId count
int taskId = 0;
//Create a blank list of tasks
List<Task> tasks = new List<Task>();
//Progress instance to show task result when task is still runnning
var progressReport = new Progress<ActionLog>((actionLog) => reportOfficeName(actionLog));
foreach (var datalist in bigDataList) 
{                   
    try
    {
        taskId++; //Increase the count
        Task task = new Task((Object obj) => {
            /// Need to cast the passed in task id to integer
            int id = (int)obj;
            RandomMethod(datalist, progressReport, cancellationToken, _setting, id);

        }, taskId, cancellationToken); //Pass the id into task

        task.Start();
        tasks.Add(task);
    }
    catch (Exception ex)
    {
        if (ex is OperationCanceledException)
        {
            throw new OperationCanceledException("Task cancelled");
        }
        else
        {
            continue;
        }
    }
} 
Task.WaitAll(tasks.ToArray());

Then, to get the id, I just report the id:

Private void RandomMethod (List<Data> datalist,IProgress<ActionLog> progress, CancellationToken token, int taskId ){
    foreach (var data in datalist){
        //report the taskId along with other parameters back to UI 
        progress.Report(new ActionLog() { TaskId = taskId });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM