Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Threads and delegates — I don't fully understand their relations

Tags:

I wrote a code that looks somewhat like this:

Thread t = new Thread(() => createSomething(dt, start, finish) );
t.Start();

And it works (sometimes it almost feel like there are multiple threads).

Yet I don't use any delegates.

  1. What is the meaning of a tread without a delegate?
  2. If a delegate is necessary — then please tell me what and how the connection is made to the delegate.
like image 886
Asaf Avatar asked Sep 25 '10 08:09

Asaf


People also ask

How do you explain delegates?

Delegation refers to the transfer of responsibility for specific tasks from one person to another. From a management perspective, delegation occurs when a manager assigns specific tasks to their employees.

What is the difference between action and delegate?

The only difference between Action Delegates and Function Delegates is that Action Delegates does not return anything i.e. having void return type.

Why delegates are useful?

Delegates allow methods to be passed as parameters. Delegates can be used to define callback methods. Delegates can be chained together; for example, multiple methods can be called on a single event. Methods don't have to match the delegate type exactly.

Is thread delegate in C#?

The Thread class in C# provides the following 4 constructors. Thread(ThreadStart start): It initializes a new instance of the Thread class. Here, the parameter start specifies a ThreadStart delegate that represents the methods to be invoked when this thread begins executing.


2 Answers

Multi-threading is very complex. You are cutting and pasting code without even learning anything about the most basic aspects of threading - how to start a thread. Pasting something off the web into a UI to fix or tweak a control, is one thing. This is a completely different kind of process. You need to study the subject, write all your own code, and understand exactly how it works, otherwise you are just wasting your time with this.

A delegate is the .NET version of a type safe function pointer. All threads require an entry point to start execution. By definition when a primary thread is created it always runs Main() as it's entry point. Any additional threads you create will need an explicitly defined entry point - a pointer to the function where they should begin execution. So threads always require a delegate.

Delegates are often used in threading for other purposes too, mainly callbacks. If you want a thread to report some information back such as completion status, one possibility is to create a callback function that the thread can use. Again the thread needs a pointer to be able to execute the callback so delegates are used for this as well. Unlike an entry point these are optional, but the concept is the same.

The relationship between threads and delegates is secondary threads cannot just call methods like the primary app thread, so a function pointer is needed instead and delegates act as function pointers.

You do not see the delegate and you did not create one because the framework is doing it for you in the Thread constructor. You can pass in the method you want to use to start the thread, and the framework code creates a delegate that points to this method for you. If you wanted to use a callback you would have to create a delegate yourself.

Here is code without lambda expressions. SomeClass has some processing that takes a long time and is done on background threads. To help with this the SomeThreadTask has been created, and it contains the process code and everything the thread needs to run it. A second delegate is used for a callback when the thread is done.

Real code would be more complicated, and a real class should never have to know how to create threads etc so you would have manager objects.

// Create a delegate for our callback function.
public delegate void SomeThreadTaskCompleted(string taskId, bool isError);


public class SomeClass
{

    private void DoBackgroundWork()
    {
        // Create a ThreadTask object.

        SomeThreadTask threadTask = new SomeThreadTask();

        // Create a task id.  Quick and dirty here to keep it simple.  
        // Read about threading and task identifiers to learn 
        // various ways people commonly do this for production code.

        threadTask.TaskId = "MyTask" + DateTime.Now.Ticks.ToString();

        // Set the thread up with a callback function pointer.

        threadTask.CompletedCallback = 
            new SomeThreadTaskCompleted(SomeThreadTaskCompletedCallback);


        // Create a thread.  We only need to specify the entry point function.
        // Framework creates the actual delegate for thread with this entry point.

        Thread thread = new Thread(threadTask.ExecuteThreadTask);

        // Do something with our thread and threadTask object instances just created
        // so we could cancel the thread etc.  Can be as simple as stick 'em in a bag
        // or may need a complex manager, just depends.

        // GO!
        thread.Start();

        // Go do something else.  When task finishes we will get a callback.

    }

    /// <summary>
    /// Method that receives callbacks from threads upon completion.
    /// </summary>
    /// <param name="taskId"></param>
    /// <param name="isError"></param>
    public void SomeThreadTaskCompletedCallback(string taskId, bool isError)
    {
        // Do post background work here.
        // Cleanup the thread and task object references, etc.
    }
}


/// <summary>
/// ThreadTask defines the work a thread needs to do and also provides any data 
/// required along with callback pointers etc.
/// Populate a new ThreadTask instance with any data the thread needs 
/// then start the thread to execute the task.
/// </summary>
internal class SomeThreadTask
{

    private string _taskId;
    private SomeThreadTaskCompleted _completedCallback;

    /// <summary>
    /// Get. Set simple identifier that allows main thread to identify this task.
    /// </summary>
    internal string TaskId
    {
        get { return _taskId; }
        set { _taskId = value; }
    }

    /// <summary>
    /// Get, Set instance of a delegate used to notify the main thread when done.
    /// </summary>
    internal SomeThreadTaskCompleted CompletedCallback
    {
        get { return _completedCallback; }
        set { _completedCallback = value; }
    }

    /// <summary>
    /// Thread entry point function.
    /// </summary>
    internal void ExecuteThreadTask()
    {
        // Often a good idea to tell the main thread if there was an error
        bool isError = false;

        // Thread begins execution here.

        // You would start some kind of long task here 
        // such as image processing, file parsing, complex query, etc.

        // Thread execution eventually returns to this function when complete.

        // Execute callback to tell main thread this task is done.
        _completedCallback.Invoke(_taskId, isError);


    }

}
}
like image 148
Sisyphus Avatar answered Sep 24 '22 07:09

Sisyphus


You are using a delegate - this is just C# syntactic sugar for:

Thread t = new Thread(new ThreadStart( () => createSomething(dt, start, finish))); 
t.Start();

The compiler is inferring from the lambda expression and the different overloads that the Thread constructor has, that your intent is to:

  • Create an instance of the ThreadStart delegate.
  • Pass it as an argument to the constructor overload of Thread that accepts a ThreadStart object.

You could also equivalently write this with anonymous-delegate syntax:

 Thread t = new Thread(delegate() { createSomething(dt, start, finish); } ); 
 t.Start();

If the arguments to createSomething are not (captured) locals, you could write this without anonymous methods altogether, which should highlight the creation of the delegate far more clearly:

private void Create()
{
   createSomething(dt, start, finish))); 
}

...

Thread t = new Thread(new ThreadStart(Create)); //new ThreadStart is optional for the same reason 
t.Start();
like image 28
Ani Avatar answered Sep 23 '22 07:09

Ani