Created
April 3, 2019 00:42
-
-
Save z3nth10n/d64f669d844bd71dabef8861c88f2b99 to your computer and use it in GitHub Desktop.
Named Thread & Thread Marked
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int TaskId = new Random().Next(); | |
ThreadPool.QueueUserWorkItem(new NamedHandler<WaitCallback>(name => new WaitCallback(BackgroundRunner)).Handler($"Ninja #{TaskId}")); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace GTAMapper.Extensions.Threading | |
{ | |
public class NamedHandler<TArg> | |
{ | |
public readonly Func<string, TArg> Handler; | |
public NamedHandler(Func<string, TArg> handler) | |
{ | |
Handler = arg => | |
{ | |
using (new ThreadMarker(arg)) | |
{ | |
return handler(arg); | |
} | |
}; | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Threading; | |
namespace GTAMapper.Extensions.Threading | |
{ | |
public class ThreadMarker : IDisposable | |
{ | |
//[ThreadStatic] | |
//private static string __Name = $"Unity Thread #{Thread.CurrentThread.ManagedThreadId}"; | |
private static Dictionary<int, string> ThreadNames = new Dictionary<int, string>(); | |
public static string Name | |
{ | |
get | |
{ | |
lock (ThreadNames) | |
{ | |
try | |
{ | |
return ThreadNames[Thread.CurrentThread.ManagedThreadId]; | |
} | |
catch | |
{ | |
return $"Unity Thread #{Thread.CurrentThread.ManagedThreadId}"; | |
} | |
} | |
} | |
} | |
public ThreadMarker(string name) | |
{ | |
lock (ThreadNames) | |
{ | |
ThreadNames.AddOrSet(Thread.CurrentThread.ManagedThreadId, name); | |
} | |
// __Name = name; | |
} | |
public void Dispose() | |
{ | |
ThreadNames.Remove(Thread.CurrentThread.ManagedThreadId); | |
// __Name = "Un-Owned"; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment