I am currently learning how to use Tasks, async and await in Windows Store ("Metro") apps. I stumbled upon the property Task.CurrentId
and try to understand how it works.
According to MSDN it returns "An integer that was assigned by the system to the currently-executing task". So I added logging this value to my custom logger, but to my surprise none of my test apps ever logged anything but null
.
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 these ids are null
. Why? This code does create tasks, doesn't it? Shouldn't they have an id?
Because you're using async / await
, all your Task.CurrentId
calls are happening on the UI thread.
The UI thread is not a Task
, so it has a null CurrentId
If you create a Task
, its CurrentId
will be set:
int? idTask = await Task.Run( () => Task.CurrentId );