. Net multithreaded Programming Knowledge grooming

Source: Internet
Author: User

1.Using System.Threading;
Multithreading is a contractor, let the 10 workers under hand to move bricks.

------------thread without any parameters passed in
2.ThreadStart ts = new ThreadStart (func of a thread a);
Thread th = new thread (TS);
Th. Start ();

public void a thread A's func ()
{
Console.WriteLine ("Thread A got things done!") ");
Console.readkey ();
}

Principle Analysis
2.1 ThreadStart prototype is a delegate type:
public delegate void ThreadStart ();
2.2 ThreadStart This delegate type is not any of the arguments passed in

The following can allow ThreadStart to receive parameters
public class MyThread
{
Private double _width = 10.0;
Private double _height = 9.0;
Private double result = 0.0;
Public MyThread (double width,double height)
{
This._width = width;
This._height = height;
}

public void Mythreadexc ()
{
Console.WriteLine ("MyThread Execute Start ...");
Thread.Sleep (2000);
result = _width * _height;
Console.WriteLine ("MyThread Execute done:the result is {0}", result);
}
}

static void Main (string[] args)
{
MyThread th = new MyThread (5.0,3.0);
Thread t = new Thread (new ThreadStart (TH). MYTHREADEXC));
T.start ();
Console.readkey ();
}


------------Thread with parameters
3.ParameterizedThreadStart pts = new Parameterizedthreadstart (func of a thread B);
Thread th = new Thread (pts);
Th. Start ();

public void a thread B's Func (object param)
{
Console.WriteLine ("Thread B received the param and got things done!") ");
}

Principle Analysis
3.1 Parameterizedthreadstart prototype is a delegate type:
public delegate void Parameterizedthreadstart (object obj);
3.2 Parameterizedthreadstart This delegate type is the one that receives the object parameter.

------------with an incoming parameter and a return parameter
Just now that the main thread needs to know when the child thread is done, we can use the Thread.threadstate enumeration to judge
When the thread is threadstate==thread.stop, it can be judged that the thread has ended, and its results can be used, and if it is not, continue to do other work, or wait for another attempt. If you need to have more than one child
Threads are returned and require their return to be evaluated asynchronously, which is called thread synchronization, the following describes a method that can customize the number of parameters and return data, which is convenient to use.
Asynchronous invocation methods and callbacks using delegates
1. Func that requires an asynchronous call is defined as a delegate
2. BeginInvoke to invoke asynchronously--the first argument is a parameter, the second is the method that is called when the thread finishes executing (the difference between the review invoke and the BeginInvoke)

Delegate Double myjobdelegate (double D);

Static Myjobdelegate MyJob;

Double jobresult=0.0;

static void Main (string[] args)
{
MyJob = new Myjobdelegate (JOB1);
Myjob.begininvoke (5.09,new AsyncCallback (Job1done), NULL)
}

Static Double Job1 (double D)
{
return d*math.pi;
}

static void Job1done (IAsyncResult result)
{
Console.WriteLine (Myjob.endinvoke (Result));
}

Asynchronous asynchronous
Synchronous synchronization
[There are many ways to use threading in C #, and the BeginInvoke and EndInvoke methods of using delegates are one of them.] The BeginInvoke method can use threads to asynchronously execute the method that the delegate points to. The return value of the method is then obtained through the EndInvoke method
(The return value of the EndInvoke method is the return value of the called method), or the method has been successfully called. ]

-------------thread Pool
Although the thread is a good thing, but also a large resource consumption, we need to use multi-threading, but do not want to thread too much, the mechanism of the thread pool came into being. NET provides us with a ready-made threadpool, which he uses as follows:

///
First, this is the callback method that thread pool threads will perform
///
Using System;
Using System.Runtime.InteropServices;

Namespace System.Threading
{
Summary:
Represents the callback method to be executed by thread pool threads.
//
Parameters:
State
An object that contains the information to be used by the callback method.
[ComVisible (True)]
public delegate void WaitCallback (object state);
}

static WaitCallback wait;

static void Main (string[] args)
{
wait = new WaitCallback (MYJOB);
ThreadPool.QueueUserWorkItem (wait,1.0);
ThreadPool.QueueUserWorkItem (wait,2.0);
ThreadPool.QueueUserWorkItem (wait,3.0);
ThreadPool.QueueUserWorkItem (wait,4.0);
Console.readkey ();
}

private static void MyJob (Object obj)
{
Double d= (double) obj;
Console.WriteLine ("Job Exec Result: {0}", D*math.pi);
}


-------------Control rights
Scenario: If the Winfrom program main thread creates a control TextBox1, and then a child thread starts to create and work, producing a return value, if the return value is returned to TextBox1 at this point, the program will error: Prohibit access to the control across threads;
So at this point we need to use a method of the control: BeginInvoke or invoke, this method can switch the execution context back to the thread that created the control:
delegate void Changetextboxdelegate (string newtext);

private void Button1_Click (Object Sender,eventargs e)
{
Parameterizedthreadstart pts = new Parameterizedthreadstart (MYJOB);
Thread th = new Thread (pts);
Th. Start (1.09);
}

----------------Scenario 1---------------
private void MyJob (Object obj)
{
This. BeginInvoke (New Changetextboxdelegate (this. Textbox1.appendtext)), ((double) obj * Math.PI). ToString ());
}


or (recommended)
----------------Scenario 2--------------
private void Settextbox1text (string text)
{
if (textbox1.invokerequired)
{
Changetextboxdelegate ct = settextbox1text;
Textbox1.begininvoke (Ct,text);
}
Else
{
TextBox1.Text = Text;
}
}

private void MyJob (Object obj)
{
Settextbox1text (double) obj * Math.PI). ToString ());
}
Reference: http://www.cnblogs.com/yizhu2000/archive/2007/10/12/922637.html

. Net multithreaded Programming Knowledge grooming

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.