1

The following code is common:

Work w = new Work();
w.Data = 42;
threadDelegate = new ThreadStart(w.DoMoreWork);
newThread = new Thread(threadDelegate);
newThread.Start();

I just wonder, why there must be a delegate to bridge the Thread and the Method to execute on that thread?

Could we just send the method name to the Thread directly?

Damith
  • 62,401
  • 13
  • 102
  • 153
smwikipedia
  • 61,609
  • 92
  • 309
  • 482

2 Answers2

5

Could we just send the method name to the Thread directly?

As a string? Ewww. If not as a string, how would you propose telling the thread what to execute? A delegate is the idiomatic way of representing "something to execute with a particular signature" in .NET.

Note that you don't need to use new ThreadStart or use a separate variable. This works fine using method group conversions:

newThread = new Thread(w.DoMoreWork);
newThread.Start();

Or if you won't need all those variables:

new Thread(new Work { Data = 42 }.DoWork).Start();

EDIT: Note that as of .NET 4, it's generally a better idea to use the Task Parallel Library for this sort of thing.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • @SteveTownsend: Indeed. Will add that to the answer if that's okay, given that it's a good idea :) – Jon Skeet Apr 19 '12 at 14:47
  • 2
    Btw Jon, is there any relation between a managed delegate and a C function pointer beyond the similar usage (e.g. to start a thread)? I know that most likely the delegate holds an internal list of methods since it has the `+=` operator, but what else can be said here? – Tudor Apr 19 '12 at 15:23
2

A delegate represents a data type just like Integer or Double represent their respective data types. A delegate defines a class of functions that are identified by their signature (return type and parameters). Just like an Integer method parameter specifies that an Integer value is expected, a delegate specifies that a method with a particular signature is expected. You need to specify the type of function that is expected for the same reasons that primitive data types are used. When you pass in your function, it's passing a pointer to the function, or object method that you want to invoke, i.e. the place in memory where that function is defined. If you just passed in a function name as a string it would not know where the function by that name is; unless you somehow defined the class containing the definition for the function you want called.

See the following for more info on delegates:

Info on C# delegates from Microsoft

stackoverflow question - why-do-we-need-c-sharp-delegates

The following link is an example of using reflection in Java to invoke methods by name. As you can see you need to specify which class contains the method you want to invoke. The actual parameter to a delegate is a pointer directly to the method, which is why the signature must match.

Java reflection

Community
  • 1
  • 1
TheSecretSquad
  • 303
  • 2
  • 14