Search code examples
c#multithreadingxamarinportable-class-library

Get thread information in Xamarin PCL


I start some parallel tasks from a PCL with

Parallel.Invoke(() => ExecuteTaskAAsync(), () => ExecuteTaskBAsync());

Now I want to know on which thread these tasks are running.

Thread.CurrentThread.ManagedThreadId seems to be only available in the iOS and Droid project but not in the PCL or UWP project. What are my possibilities? If I would use DependencyService I also won't know on which thread TaskA is running, because there is not relationship between the started task and DependencyService.

How can I get thread information (id, name, ...) in a PCL?

When you set a breakpoint you can get into the Tasks Window and get some more information. Also you have a drop down on the top to select a process, choose between different threads and get some info about the stack frame. So one should be able to also get this information in code?

Edit:

Seems that the informations in the Tasks Window is only available when running on UWP.


Solution

  • The concept of threads is completely absent in Windows Universal Apps and the use of tasks is recommended instead of threads.

    I haven't found official documentation on the reasons behind it, but there's an ongoing discussion at the CoreFX's github repo.

    So it looks like what you are looking for isn't currently possible if you want to support UWP projects.

    You mal alternatively look for the TaskScheduler that manages the currently running task:

    var poolId = TaskScheduler.Current.Id;
    

    This way you can at least find out, if your method is running on the same ThreadPool (eg: They are executed on any background threads, or the UI thread).

    As far as I know, to find the TaskScheduler for the UI, you have to call TaskScheduler.Current.Id while you are on the UI Thread and just store it in a variable.