Part 86   Multithreading in C#

What is a Process:

Process is what the operating system uses to facilitate(帮助) the execution of a program by providing the resources required.Each process has unique process Id associated with(关联) it. You can view the process within which a program is being executed using windows task manager.

What is Thread:

Thread is a light weight(轻量级) process.A process has at least one thread which is commonly called(通常被称为) as main thread which actually executes the application code. A single process can hava multiple threads.

Please Note: All the threading related classes are present in(存在于) System.Threading namespace.

Part 87   Advantages and disadvantages of multithreading

Advantages of multithreading:

1, To maintain a responsive user interface(快速响应用户界面)

2, To make effcient use of processor time while waiting for I/O operations to complete.(适当的利用处理器,在等待I / O操作完成的这段时间。)

3, To split large, CPU-bound tasks to be processed simultaneously on a machine that has multiple processors/cores(分割大cpu密集型任务处理的机器上同时有多个处理器/核心)

Disadvantages of multithreading:

1, On a single processor/core machine threading can affect performance negatively as there is overhead involved with context-switching.(在单个处理器/核心的机器,线程会对上下文切换开销的性能有负面影响)

2, Have to write more lines of code to accomplish the same task.(需要编写更多的代码来完成相同的任务)

3,Multithreaded applications are difficult to write, understand, debug and maintain.(多线程应用程序很难写,理解、调试和维护。)

Please Note: Only use multithreading when the advantages of doing so outweigh the disavantages.

Part 88   ThreadStart delegate

To create a Thread, create an instance of Thread class and to it's constructor pass the name of the function that we want the thread to execute.

class Program
    {
        static void Main(string[] args)
        {
            Thread t = new Thread(Number.Print);
            t.Start();
        }
    }

    public class Number
    {
        public static void Print()
        {
            for(int i=0;i<10;i++)
            {
                Console.WriteLine(i);
            }
        }
    }
Thread

相关文章:

  • 2021-07-09
  • 2021-05-28
  • 2021-09-05
  • 2021-10-22
  • 2021-10-19
猜你喜欢
  • 2022-01-12
  • 2021-06-17
  • 2022-03-07
  • 2021-12-21
  • 2022-01-13
相关资源
相似解决方案