Passing a task instance to a task delegate

I have a long Task job that uses callbacks to send data step by step (rather than a single ContinueWith () callback at the end).

I want to be able to pass the Task object back to this callback for the purpose of identifying the task (using Task.CurrentId)

However, I cannot decide how to pass the Task object to the task delegate. There seems to be no overload for this, and I cannot use closure to do this, since the task object is not defined at this point.

eg.

public Task StartDoingSomeStuff(CallbackDelegate callback) { Task task = Task.Factory.StartNew(() => { while(whatever) { var results = DoSomeStuff(); callback(results, task); //CS0165. How do I get hold of the task? } }); return task; } 

gives:

error CS0165: use of an unassigned local variable 'task'

+4
source share
3 answers

Split, declaring a variable and assigning a task to it, in two operators. Make sure you do not use the variable before assigning the task:

 public Task StartDoingSomeStuff(CallbackDelegate callback) { var gate = new object(); lock (gate) { Task task = null; task = Task.Factory.StartNew(() => { lock (gate) { while (whatever) { var results = DoSomeStuff(); callback(results, task); } } }); return task; } } 
+5
source

Another solution is to create a task key and dictionary matching keys for tasks, and then transfer the key as a state to the task action:

 var taskMap = new Dictionary<object, Task>(); var taskKey = new object(); taskMap.Add(taskKey, Task.Factory.StartNew(key => { callback(results, key); }, taskKey)); 

Of course, you need to look for the task from the key, which may or may not suit your scenario.

+1
source

This should work, although this is bad practice:

 public Task StartDoingSomeStuff(CallbackDelegate callback) { Task task = null; task = Task.Factory.StartNew(() => { while(whatever) { var results = DoSomeStuff(); callback(results, task); //CS0165. How do I get hold of the task? } }); return task; } 
0
source

Source: https://habr.com/ru/post/1387186/


All Articles