Definition and use of C# and WPF multithreading

Windows system is a multi-threaded operating system. Process is a basic concept in Windows system. It contains the resources needed to run programs. A running application is regarded as a process in the operating system. A process can include one or more threads. Thread is the basic unit for the operating system to allocate processor time. Multiple threads can execute code at the same time. Processes are relatively independent. One process cannot access the data of another process (unless using distributed computing), and the failure of one process will not affect the operation of other processes. Windows system uses processes to divide work into multiple independent areas. Process can be understood as the basic boundary of a program. It is a running routine of the application and a dynamic execution process of the application.

Advantages of multithreading:

1. Multithreading can improve CPU utilization, because when a thread is waiting, the CPU will execute another thread

2. By improving the utilization of CPU, the overall execution speed of the program can be directly improved

Disadvantages of multithreading:

1. The more threads are opened, the larger the memory consumption

2. It is more difficult to coordinate and manage code, which requires CPU time to track threads

3. The sharing of resources between threads may cause unknown problems

Multithreading definition:

Threads without parameters:

private void Main()
    Thread t1 = new Thread(new ThreadStart(ThreadMethod)); 
    t1.IsBackground = true;//Default background thread

private void ThreadMethod()
//Thread method 

Thread with parameters: parameter type of ParameterizedThreadStart delegate must be Object

private void Main()
    Thread t1 = new Thread(new ParameterizedThreadStart(ThreadMethod)); 
    t1.IsBackground = true;
    t1.Start("thread param");

private void ThreadMethod(object param)
    //Thread method 

Assign a value to the Thread constructor using an anonymous delegate or Lamba expression:

//Create by anonymous delegate
Thread thread1 = new Thread(delegate() { Console.WriteLine("I create threads through anonymous delegates"); });
//Create by Lambda expression
Thread thread2 = new Thread(() => Console.WriteLine("I passed Lambda Delegate created by expression"));

IsBackground: the application can end only when all foreground threads end. By default, all threads created are foreground threads. As long as all foreground threads end, the background threads end automatically. Set the background thread through Thread.IsBackground. The thread type must be set before calling the Start method, otherwise once the thread runs, its type cannot be changed

Join: blocks the calling thread until it terminates

Abort: throw ThreadAbortException to terminate the thread. The terminated thread cannot wake up

Suspend and Resume: obsolete. Since the execution sequence of threads and the execution of programs are unpredictable, the use of suspend and Resume is prone to deadlock, which should be used as little as possible in practical applications

Sleep: suspend the running thread for a period of time

Priority: about Normal belownormal highest lowest Normal. The default value is Normal

Thread pool: because the creation and destruction of threads require a certain overhead, excessive use of threads will cause a waste of memory resources. For performance reasons, the concept of thread pool is introduced. The thread pool maintains a request queue. The code of the thread pool extracts tasks from the queue and then delegates them to a thread of the thread pool for execution. The thread will not be destroyed immediately after execution. This can not only execute tasks in the background, but also reduce the expenses caused by thread creation and destruction. (usage scenario: 1. The processing time of a single task is relatively short    2. Number of tasks to be handled (large)

//Set the maximum number of threads in the thread pool to reduce the memory occupied by creation resources
ThreadPool.SetMaxThreads (int workerThreads,int completionPortThreads);
//Thread without parameters
ThreadPool.QueueUserWorkItem(new WaitCallback(Method name));
//Thread with parameters
ThreadPool.QueueUserWorkItem(new WaitCallback(Method name), parameter);

Thread synchronization: it means that only one thread can access variables at a certain time, using the lock keyword

expression Represents the object you want to track:
If you want to protect an instance of a class, generally, you can use this;
If you want to protect a static variable (for example, the mutually exclusive code segment is inside a static method), you can generally use the class name
 lock(this)Try not to use this. This refers to the entire outer method. When locked, other processes cannot access this method. A private object that does not affect other operations should be locked

Asynchronous callback: if you want to perform an operation after the completion of an asynchronous method, you can use asynchronous callback

Action<string> action = this.DoSomethingLong;
// Define a callback
AsyncCallback callback = p =>
       Console.WriteLine($"Execute after asynchronous completion");
// Callback as parameter
action.BeginInvoke("btnAsyncAdvanced_Click", callback, null);

Tags: C# WPF

Posted on Sun, 31 Oct 2021 01:01:01 -0400 by AnthonyArde