How does Task.CurrentId work?

I am currently learning how to use Tasks, async and wait in Windows Store apps ("Metro"). I came across the Task.CurrentId property and try to understand how it works.

According to MSDN, it returns "The integer that has been assigned by the system for the task currently being performed." Therefore, I added the registration of this value to my own registrar, but, to my surprise, none of my test applications ever registered anything except null .

Take a look at this example:

 private async void TestButton_Click(object sender, RoutedEventArgs e) { int? id1 = Task.CurrentId; await Task.Delay(100); int? id2 = Task.CurrentId; StorageFolder folder = ApplicationData.Current.LocalFolder; StorageFile file = await folder.CreateFileAsync("test.txt", CreationCollisionOption.OpenIfExists); int? id3 = Task.CurrentId; await FileIO.AppendTextAsync(file, "test"); int? id4 = Task.CurrentId; await DoMoreAsync(); int? id7 = Task.CurrentId; } private async Task DoMoreAsync() { StorageFolder folder = ApplicationData.Current.LocalFolder; StorageFile file = await folder.CreateFileAsync("test.txt", CreationCollisionOption.OpenIfExists); int? id5 = Task.CurrentId; await FileIO.AppendTextAsync(file, "test"); int? id6 = Task.CurrentId; } 

All of these identifiers are null . What for? This code really creates tasks, doesn't it? Should they have an identifier?

+7
source share
2 answers

Since you are using async / await , all your Task.CurrentId calls happen in the user interface thread.

The UI thread is not Task , therefore null CurrentId


If you create a Task , its CurrentId will be set:

 int? idTask = await Task.Run( () => Task.CurrentId ); 
+10
source

According to MSDN, it returns "The integer assigned by the system for the currently executing task" ... This code really creates the tasks, doesn't it? Should they have an identifier?

The key is "running now."

There are two types of Task s: one type of task executes code, and the other type of task is just an abstract representation of an operation or event. For example, Task.Run will create a code execution task that will execute its code in a thread pool thread; Task.Delay will create an operation / event task that will end when the timer fires.

The tasks returned by async methods represent the method itself, so they are actually an operation / event, not a code task. The code in async methods can run as delegates or as several different tasks (or a mixture of them). Even if you get CurrentId from the async method (which indicates that you are working inside a code execution task), this identifier will be different from the task identifier returned by the method (which is always an operation / event).

+8
source

All Articles