Gossip "multi-thread"

Source: Internet
Author: User
Document directory
  • Create a simple thread:
  • Create a thread with parameters:
  • Use timer to create a thread:
  • Use threadpool to create a thread without parameters:
  • Use threadpool to create a thread with parameters:
  • Create a thread using anonymous delegation:
  • Create a thread using lambda:
  • Thread update UI (custom delegate mode ):
  • Thread update UI (commissioned by Action)
  • Thread update UI (commissioned by func)
  • Thread update UI (commissioned by predicate)
  • Predicate Delegation
  • Func Delegation
  • Action delegate

 

1. What is a process?

"Process" is the most basic and important concept of the operating system. Simply put, a process is the application you are executing. A process contains one or more threads. A process in the system must correspond to an application, but the same application may have multiple processes. Therefore, we must be clear that processes and programs are associated, but they are not the same concept. That is, the process is called after the application is loaded into the memory.

What is a thread?

A thread is simply an execution stream in the program. Each thread has its own proprietary register and the code zone is shared. That is, different threads can execute the same function and access the same variable. That is, the process is called a thread when it is processed by the CPU.

What is multithreading? 

 Multithreading is simply to say that a program contains multiple program streams, and a complex operation can be divided into multiple detailed operations. These Detailed operations can be executed in parallel, this saves time and improves efficiency.

Advantages of multithreading:

 Threads can have the following benefits: they can improve CPU utilization. In a multi-threaded program, when a thread is waiting, the CPU can run other threads for processing, which saves time and improves program efficiency, it also improves the user experience.

Multithreading disadvantages:  

1. The more threads, the larger the memory usage;

2. multi-threaded operations require coordination and unified management, and the CPU will track additional threads;
3. Inter-thread access to shared resources will affect each other, and various problems of competing to share resources must be solved;
4. Too many threads will increase the complexity of control and lead to unnecessary bugs;

5. There are also differences in the execution sequence between 32-bit operating systems, 64-bit operating system execution threads, and different versions of operating systems.

Important concepts (this article does not focus on)

Start (): Start the thread;
Sleep (INT): The number of milliseconds specified by the current thread to be suspended;
Abort (): This method is usually used to terminate a thread, but it is prone to errors;
Suspend (): suspends a thread and can be recovered if needed;
Resume (): restores the thread suspended by the suspend () method;

The priority of a program can be defined as the value of threadpriority enumeration, that is, highest, abovenormal, normal, belownormal, and lowest;

Three methods can be used to create a thread: thread, threadpool, and timer;

The. NET Framework provides three built-in timer types: system. Windows. Forms. Timer, system. Timers. timer, and system. Threading. Timer;

Thread Synchronization lock, monitor, synchronization event eventwaithandler, mutex, thread pool, etc;

Ii. multithreading practices

In this article, we will use 11 small demos to explain the multi-thread practice. It is not very comprehensive, but I just hope to give you a reference.Because it is relatively simple, I will not add Redundant text descriptions, so that everyone looks more comfortable.I will add code to the end of the article. You can download it for viewing and debugging.

The 11 methods are all called through form1_load, as shown in the following code and image:

private void Form1_Load(object sender, EventArgs e)
{
DoWithEasy();
DoWithParameter();
DoWithTimer();
DoWithThreadPool();
DoWithThreadPoolParameter();
DoWithAnonymous();
DoWithLambda();
DoWithCommon();
DoWithAction();
DoWithFunc();
DoWithPredicate();
}

 

Create a simple thread:
private void DoWithEasy()
{
Thread t = new Thread(new ThreadStart(this.DoSomethingWithEasy));
t.Start();
}
private void DoSomethingWithEasy()
{
MessageBox.Show("Knights Warrior");
}
Create a thread with parameters:
private void DoWithParameter()
{
Thread t = new Thread(new ParameterizedThreadStart(this.DoSomethingWithParameter));
t.Start("Knights Warrior");
}
private void DoSomethingWithParameter(object x)
{
MessageBox.Show(x.ToString());
}

 

Use timer to create a thread:
public void DoWithTimer()
{

System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
timer.Interval = 1000;
timer.Tick += (x, y) =>
{
MessageBox.Show("Knights Warrior");
};
timer.Start();
}
Use threadpool to create a thread without parameters:
private void DoWithThreadPool()
{
ThreadPool.QueueUserWorkItem(new WaitCallback(this.DoSomethingWithThreadPoolNO));
}
private void DoSomethingWithThreadPoolNO(object x)
{
MessageBox.Show("Knights Warrior");
}
Use threadpool to create a thread with parameters:
private void DoWithThreadPoolParameter()
{
ThreadPool.QueueUserWorkItem(new WaitCallback(this.DoSomethingWithThreadPoolParameter), "Knights Warrior");
}
private void DoSomethingWithThreadPoolParameter(object x)
{
MessageBox.Show(x.ToString());
}
Create a thread using anonymous delegation:
private void DoWithAnonymous()
{
ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object x)
{
MessageBox.Show("Knights Warrior");
}));
}
Create a thread using lambda:
private void DoWithLambda()
{
ThreadPool.QueueUserWorkItem(new WaitCallback(x =>
{
MessageBox.Show("Knights Warrior");
}));
}
Thread update UI (custom delegate mode ):
private void DoWithCommon()
{
WaitCallback waitCallBack = new WaitCallback(this.InvokeMethod);
ThreadPool.QueueUserWorkItem(waitCallBack, "Knights Warrior");
}

private delegate void InvokeMethodDelegate(string name);
private void InvokeMethod(object x)
{
this.Invoke(new InvokeMethodDelegate(this.ChangeUIWithCommon), x.ToString());
}

private void ChangeUIWithCommon(string name)
{
this.lblMessage.Text = name;
}

 

Thread update UI (commissioned by Action)
private void DoWithAction()
{
WaitCallback waitCallback = new WaitCallback(this.DoSomethingWithAction);
ThreadPool.QueueUserWorkItem(waitCallback, "Knights Warrior");
}

private void DoSomethingWithAction(object x)
{
this.Invoke(new Action<string>(this.ChangeUI), x.ToString());
}

private void ChangeUI(string message)
{
this.lblMessage.Text = message;
}
Thread update UI (commissioned by func)
private void DoWithFunc()
{
WaitCallback waitCallback = new WaitCallback(this.DoSomethingWithFunc);
ThreadPool.QueueUserWorkItem(waitCallback, "Knights Warrior");
}

private void DoSomethingWithFunc(object x)
{
Func<string, int> f = new Func<string, int>(this.GetFuncMessage);
object result = this.Invoke(f, x.ToString());
MessageBox.Show(result.ToString());
}

private int GetFuncMessage(string message)
{
this.lblMessage.Text = message;
if (message == "Knights Warrior")
{
return 1;
}
else
{
return 0;
}
}

 

Thread update UI (commissioned by predicate)
private void DoWithPredicate()
{
WaitCallback waitCallback = new WaitCallback(this.DoSomethingWithPredicate);
ThreadPool.QueueUserWorkItem(waitCallback, "Knights Warrior");
}

private void DoSomethingWithPredicate(object x)
{
Predicate<string> pd = new Predicate<string>(this.GetPredicateMessage);
object result = this.Invoke(pd, x);
MessageBox.Show(result.ToString());
}

private bool GetPredicateMessage(string message)
{
this.lblMessage.Text = message;
if (message == "Knights Warrior")
{
return true;
}
else
{
return false;
}
}

 

Concept annotation: predicate Delegation
Definition:Public Delegate bool predicate <t> (t obj );

 

Defines a set of conditions and determines whether the specified object meets these conditions. This delegate is often used by several methods of the array and List classes to retrieve elements in the collection.

Func Delegation
Definition:Public Delegate tresult func <t, tresult> (T Arg );
 
Code

Delegate tresult func <t> ();
Delegate tresult func <t1, tresult> (T1 arg1 );
Delegate tresult func <T1, T2, tresult> (T1 arg1, T2 arg2 );
Delegate tresult func <T1, T2, T3, tresult> (T1 arg1, T2 arg2, T3 arg3 );
Delegate tresult func <T1, T2, T3, T4, tresult> T1 arg1, T2 arg2, T3 arg3, T4 arg4 );

Func (): encapsulate a method that does not have a parameter and returns a tresult type value.
Func <t, tresult> encapsulates a method with a parameter and returns a tresult type value.

Action delegate
Definition:Public Delegate void action <t> (t obj );
Code

Delegatevoid action <t> (T1 arg1 );
Delegatevoid action <T1, T2> (T1 arg1, T2 arg2 );
Delegatevoid action <T1, T2, T3> T1 arg1, T2 arg2, T3 arg3 );
Delegatevoid action <T1, T2, T3, T4> T1 arg1, T2 arg2, T3 arg3, T4 arg4)

Action <T1, T2>: encapsulate a method with two parameters and without return values.

These three delegates are often used, and the distinction is also very simple:
Predicate accepts a t parameter and returns a bool value. You can use
Func implements this function;
Func accepts 1 to 4 parameters and returns a value;

Action accepts 1 to 4 parameters and does not return values;

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.