I am wondering why .Net does not have a generic method for starting a thread.
For example we start a thread like following....
Thread th = new Thread(SayHello);
th.Start("Hello");
private static void SayHello(object obj)
{
string str = obj as string;
Console.WriteLine(str);
}
Why can't we have I mean why .Net team did not consider making it generic ?
Something like following...
Thread<string> th = new Thread<string>(SayHello);
Because many times when I pass value types to thread start I have to do boxing/unboxing.
I can see several reasons why the people who implement BCL didn't bother writing something like this:
new Thread(() => SayHello("Hello")).Thread<T> would be a confusing type, because it's not clear what does that T stand for. Especially since it would have a completely different meaning than T in Task<T>.Thread<T> as a wrapper using 20 lines (see below).So, the issue is tiny and easy to work around if it actually bothers you and the solution could be confusing. That's most likely why resources weren't spend implementing this.
Possible implementation of Thread<T>:
class Thread<T>
{
private readonly Action<T> m_action;
private readonly Thread m_thread;
private T m_parameter;
public Thread(Action<T> action)
{
m_action = action;
m_thread = new Thread(DoWork);
}
public void Start(T parameter)
{
m_parameter = parameter;
m_thread.Start();
}
private void DoWork()
{
m_action(m_parameter);
}
}
Because no one wrote that method yet. Besides, since boxing/unboxing here is a fairly small part of the overall operation and few programmers actually need to start a thread manually (there are better abstractions for most use cases), they probably saw little need to specify, implement, test and document a change that is essentially not needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With