c illustrates several ways in which multithreading is used

  • 2020-06-07 05:12:56
  • OfStack

(1) No parameters need to be passed or returned

ThreadStart is a delegate defined as void ThreadStart() with no arguments and return values.


class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 30; i++)
{
ThreadStart threadStart = new ThreadStart(Calculate);
Thread thread = new Thread(threadStart);
thread.Start();
}
Thread.Sleep(2000);
Console.Read();
}
public static void Calculate()
{
DateTime time = DateTime.Now;// Get the current time 
Random ra = new Random();// Random number object 
Thread.Sleep(ra.Next(10,100));// Random dormancy 1 Period of time 
Console.WriteLine(time.Minute + ":" + time.Millisecond);
}
}

(2) A single parameter needs to be passed

The ParameterThreadStart delegate is defined as void ParameterizedThreadStart(object state) and has 1 argument but no return value.


class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 30; i++)
{
ParameterizedThreadStart tStart = new ParameterizedThreadStart(Calculate);
Thread thread = new Thread(tStart);
thread.Start(i*10+10);// Passing parameters 
}
Thread.Sleep(2000);
Console.Read();
}
public static void Calculate(object arg)
{
Random ra = new Random();// Random number object 
Thread.Sleep(ra.Next(10, 100));// Random dormancy 1 Period of time 
Console.WriteLine(arg);
}
}

(3) Use special thread classes (commonly used)

Using thread class can have multiple parameters and multiple return values, 10 points flexible!


class Program
{
static void Main(string[] args)
{
MyThread mt = new MyThread(100);
ThreadStart threadStart = new ThreadStart(mt.Calculate);
Thread thread = new Thread(threadStart);
thread.Start();
   // Wait for the thread to end 
while (thread.ThreadState != ThreadState.Stopped)
{
Thread.Sleep(10);
}
Console.WriteLine(mt.Result);// Print return value 
Console.Read();
}
}
public class MyThread// Thread class 
{
public int Parame { set; get; }// parameter 
public int Result { set; get; }// The return value 
// The constructor 
public MyThread(int parame)
{
this.Parame = parame;
}
// Thread execution method 
public void Calculate()
{
Random ra = new Random();// Random number object 
Thread.Sleep(ra.Next(10, 100));// Random dormancy 1 Period of time 
Console.WriteLine(this.Parame);
this.Result = this.Parame * ra.Next(10, 100);
}
}

(4) Use anonymous methods (commonly used)

Starting a thread with an anonymous method can have multiple arguments and return values, and it's easy to use!


class Program
{
static void Main(string[] args)
{
int Parame = 100;// As a parameter 
int Result = 0;// As the return value 
// Anonymous methods 
ThreadStart threadStart = new ThreadStart(delegate()
{
Random ra = new Random();// Random number object 
Thread.Sleep(ra.Next(10, 100));// Random dormancy 1 Period of time 
Console.WriteLine(Parame);// Output parameters 
Result = Parame * ra.Next(10, 100);// Calculate the return value 
});
Thread thread = new Thread(threadStart);
thread.Start();// Multiple threads start anonymous methods 
// Wait for the thread to end 
while (thread.ThreadState != ThreadState.Stopped)
{
Thread.Sleep(10);
}
Console.WriteLine(Result);// Print return value 
Console.Read();
}
}

(5) Using delegate to enable multi-threading (multi-threading penetration)

1. Use BeginInvoke and EndInvoke methods of delegate (Delegate) to operate the thread

The BeginInvoke method USES a thread to asynchronously execute the method 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 it is determined that the method was successfully called.


class Program
{
private delegate int NewTaskDelegate(int ms);
private static int newTask(int ms)
{
Console.WriteLine(" Task start ");
Thread.Sleep(ms);
Random random = new Random();
int n = random.Next(10000);
Console.WriteLine(" Task to complete ");
return n;
}
static void Main(string[] args)
{
NewTaskDelegate task = newTask;
IAsyncResult asyncResult = task.BeginInvoke(2000, null, null);
//EndInvoke Method will be blocked 2 seconds 
int result = task.EndInvoke(asyncResult);
Console.WriteLine(result);
Console.Read();
}
}

2. Use the IAsyncResult. IsCompleted attribute to determine whether the asynchronous call is completed


class Program
{
private delegate int NewTaskDelegate(int ms);
private static int newTask(int ms)
{
Console.WriteLine(" Task start ");
Thread.Sleep(ms);
Random random = new Random();
int n = random.Next(10000);
Console.WriteLine(" Task to complete ");
return n;
}
static void Main(string[] args)
{
NewTaskDelegate task = newTask;
IAsyncResult asyncResult = task.BeginInvoke(2000, null, null);
// Wait for the asynchronous execution to complete 
while (!asyncResult.IsCompleted)
{
Console.Write("*");
Thread.Sleep(100);
}
//  Now that the asynchronous call is complete,  EndInvoke The result is returned immediately 
int result = task.EndInvoke(asyncResult);
Console.WriteLine(result);
Console.Read();
}
}

3. Use WaitOne method to wait for the execution of the asynchronous method to complete

The first parameter of WaitOne represents the number of milliseconds to wait. For the specified time, the WaitOne method waits for 1 until the asynchronous call completes and is notified before returning true. The WaitOne method returns false when the asynchronous call is not complete after the specified time. If the specified time is 0, it does not wait; if -1, it waits forever until the asynchronous call is complete.


class Program
{
private delegate int NewTaskDelegate(int ms);
private static int newTask(int ms)
{
Console.WriteLine(" Task start ");
Thread.Sleep(ms);
Random random = new Random();
int n = random.Next(10000);
Console.WriteLine(" Task to complete ");
return n;
}
static void Main(string[] args)
{
NewTaskDelegate task = newTask;
IAsyncResult asyncResult = task.BeginInvoke(2000, null, null);
// Wait for the asynchronous execution to complete 
while (!asyncResult.AsyncWaitHandle.WaitOne(100, false))
{
Console.Write("*");
}
int result = task.EndInvoke(asyncResult);
Console.WriteLine(result);
Console.Read();
}
}

4, use callback method to return the result

It should be noted that "my.BeginInvoke(3,300, MethodCompleted, my)", the parameter passing method of BeginInvoke:

The first part (3,300) is the argument to its delegate itself.

The penultimate parameter (MethodCompleted) is the callback method delegate type. It is the delegate of the callback method. This delegate does not return a value.

The last parameter (my) needs to pass 1 value to the MethodCompleted method, usually the delegate of the called method, which can be obtained using the IAsyncResult.AsyncState attribute.


class Program
{
private delegate int MyMethod(int second, int millisecond);
// Thread execution method 
private static int method(int second, int millisecond)
{
Console.WriteLine(" Thread to sleep " + (second * 1000 + millisecond) + " ms ");
Thread.Sleep(second * 1000 + millisecond);
Random random = new Random();
return random.Next(10000);
}
// The callback method 
private static void MethodCompleted(IAsyncResult asyncResult)
{
if (asyncResult == null || asyncResult.AsyncState == null)
{
Console.WriteLine(" Callback failed!! ");
return;
}
int result = (asyncResult.AsyncState as MyMethod).EndInvoke(asyncResult);
Console.WriteLine(" Tasks completed, results: " + result);
}
static void Main(string[] args)
{
MyMethod my = method;
IAsyncResult asyncResult = my.BeginInvoke(3,300, MethodCompleted, my);
Console.WriteLine(" Task start ");
Console.Read();
}
}

5. BeginXXX and EndXXX methods for other components

There are methods similar to BeginInvoke and EndInvoke in other.net components, such as the BeginGetResponse and EndGetResponse methods of the ES103en.Net.HttpWebRequest class. Its use is similar to the BeginInvoke and EndInvoke methods of the delegate type, for example:


class Program
{
// The callback function 
private static void requestCompleted(IAsyncResult asyncResult)
{
if (asyncResult == null || asyncResult.AsyncState==null)
{
Console.WriteLine(" The callback failed ");
return;
}
HttpWebRequest hwr = asyncResult.AsyncState as HttpWebRequest;
HttpWebResponse response = (HttpWebResponse)hwr.EndGetResponse(asyncResult);
StreamReader sr = new StreamReader(response.GetResponseStream());
string str = sr.ReadToEnd();
Console.WriteLine(" Return flow length: "+str.Length);
}
static void Main(string[] args)
{
HttpWebRequest request =
(HttpWebRequest)WebRequest.Create("http://www.baidu.com");
// An asynchronous request 
IAsyncResult asyncResult = request.BeginGetResponse(requestCompleted, request);
Console.WriteLine(" Task start ");
Console.Read();
}
}


Related articles: