- Home /
How to get good profiling data with System.Threading.Tasks
Profiling for work we do on background threads via System.Threading.Tasks just shows up in the "Scripting Threads" section, and there seems to be a bug in the Unity profiling UI where the profiling label for those tasks will "jump around" (possibly due to the fact that the workers all have the same name). I tried making a helper function that would call BeginThreadProfiling only once per worker thread, but it seemed to mess up the profiler. The only way to make things look good is to call BeginThreadProfiling/EndThreadProfiling at the beginning and end of each task, but that seems pretty wasteful for profiling code. Is there a better way?
Here's what I was trying to do:
private static volatile int _threadCount = 0;
[ThreadStatic] private static int _threadId = -1;
public static void InitWorkerThread() {
if (_threadId == -1) {
_threadId = Interlocked.Increment(ref _threadCount);
Profiler.BeginThreadProfiling("My Worker Threads", $"My Worker Thread {_threadId}");
}
}
...
void someAsyncTaskFunction() {
InitWorkerThread();
Profiler.BeginSample("Some Async Task Function");
...
Profiler.EndSample();
}
I verified that the branch was being taken once per worker thread, but "My Worker Threads" wasn't showing up in the profiler, and there were like hundreds of erroneous "Some Async Task Function" entries under ScriptingThreads (definitely incorrect).
Everything works fine if we call Profiler.Begin/EndThreadProfiling in every call that we want to profile, but that seems wasteful. Is there a better way to do this?