The calling method of the delegate and the execution thread

Source: Internet
Author: User
Tags instance method

Delegates can be seen as a new type of object in C #. In general, we often pass data as parameters to a method, but sometimes a method does not refer to the operation of the data, but rather to operate on another method, which requires the use of the delegate.

A typical use of a delegate is a thread. When you try to start a thread, the Thread.Start () method you use must have a parameter that contains the contents of another method, the delegate method.

Another occasion for a delegate is an event, and GUI programming is primarily about handling events, such as the Click event that we handle in the application, but how does Windows know to invoke the click handler function of the application to respond to the Click event. This is the role of the delegate. An event is actually a special form of a delegate.

If you understand from the C + + Programmer's perspective, a delegate instance can be interpreted as a function pointer. But this direct function pointer invocation can cause problems, such as type security, and in object-oriented programming, methods cannot exist in isolation, and often need to be associated with class instances. So, in C #, you wrap these methods in a new type of object, that is, a delegate. In other words, a delegate is actually a very special type of object (consistent with the concept of a class). The difference is that previously defined objects can contain data, whereas delegates contain only method signatures.

The definition of a delegate

Defining a delegate is basically defining a new class. You can define a delegate anywhere in the definition class, or you can define a delegate inside another class. Defines a delegate whose syntax is similar to defining a method, but without a method body, preceded by a keyword delegate.

delegate void MyDelegate (string sdescription);

A delegate with a string argument and no Return (void) is defined as above. any method that has such a signature format can be viewed as an instance of this delegate, whether it is an instance method on any object or a static method .

second, the call of the delegate

Before invoking a delegate, you need to declare a delegate and bind it to a method that is actually implemented.

Private delegate void MyDelegate (string sdescription);

static void OutPut (String Spara)

{

Console.WriteLine (Spara);

}

static void Main (string[] args)

{

Declare a delegate and take output as an instance of a delegate

MyDelegate dlgt = new MyDelegate (OutPut);

Direct call to delegate

DLGT ("Call the delegate.");

}

So the program outputs "call the delegate."

Another way to invoke a delegate is to invoke it in the form of invoke, and of course the results of the two invocations are different.

third, the thread where the delegate code executes

The thread in which the delegate code executes is related to the way it was invoked, and the following example illustrates the relationship between the calling method and the execution thread.

Defining delegates
delegate void MyDelegate (string sdesp);

Delegate instance
private void Dlgtoutput (string sdesp)
{

Thread.Sleep (2000);


The name of the thread that the output code executes
Console.WriteLine (Sdesp + ", Thread name=" + Thread.CurrentThread.Name);
}

private void Threadentity ()
{
Set Child thread Name
Thread.CurrentThread.Name = "Child Thread";

Instantiating a delegate
MyDelegate dlgt = new MyDelegate (dlgtoutput);
//
Dlgtoutput ("Direct call delegate");

This. Invoke (Dlgt,new object[]{("Use Invoke Invoke Delegate")});

Console.WriteLine ("After Invoke");
}
private void Btnok_click (object sender, System.EventArgs e)
{
Set Main thread name
Thread.CurrentThread.Name = "Main Thread";

Start thread
Thread thread = new Thread (new ThreadStart (threadentity));
Thread. Start ();
}

The output of the program is:

Direct invoke delegate, thread Name=child thread
Thread Name=main thread with invoke invoke call delegate
After Invoke

Visible, different calling methods, the thread that executes the delegate is not the same.

If the delegate is invoked directly, the delegate code executes in a child thread;

If you invoke the delegate by using invoke, the delegate code is found to be executed in the main thread. Specifically, when invoking a delegate with invoke, the delegate is executed on the thread that owns the underlying window handle of the control.

Iv. Synchronous and asynchronous delegates

In fact, as can be seen from the example above, we intentionally let the Delegate Sleep (2000) in the delegate. However, it is found that "after Invoke" is always output after the output of the delegate. Visible, whether directly calling a delegate or using Invoke to invoke a delegate, is synchronized. The second invocation, from the Windows program's point of view, is like a child thread using SendMessage to send a message to the main thread, which needs to wait for the message to return, and the child thread will continue to execute.

If you need to invoke the delegate asynchronously, you need to use the BeginInvoke invocation method. Now we modify the above call:

{

......

IAsyncResult Iasync = this. BeginInvoke (DLGT, new object[]{"Use BeginInvoke invoke Delegate"});
Console.WriteLine ("After BeginInvoke");

Wait for delegate execution to complete
This. EndInvoke (Iasync);

}

This time you'll find out the order of the output results is:

"After BeginInvoke"

Use BeginInvoke to invoke the delegate, thread Name=main thread

Therefore, if you want the delegate to be executed asynchronously, you need to invoke the delegate using BeginInvoke, and the asynchronous delegate must also be executed on the owning control thread (the example is the main thread). The asynchronous invocation of a delegate is like using PostMessage to the main thread, and it does not have to wait for the message result to return.

As you can see, for delegates, the difference in how they are invoked not only determines the thread that the delegate executes, but also determines whether the delegate executes asynchronously.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.