c#中多线程与多任务区别_如何在C#中对任务使用多线程

本文介绍了C#中多线程和多任务的区别,包括线程的基本概念、线程的创建、线程池和任务并行库的使用。通过示例代码展示了如何创建和管理线程,强调了线程竞争处理器时间和线程池的优势。
摘要由CSDN通过智能技术生成

c#中多线程与多任务区别

The computer programming term "thread" is short for thread of execution, in which a processor follows a specified path through your code. The concept of following more than one thread at a time introduces the subject of multi-tasking and multi-threading.

计算机编程术语“线程”是执行线程的缩写,其中处理器遵循代码中的指定路径。 一次跟踪多个线程的概念引入了多任务和多线程的主题。

An application has one or more processes in it. Think of a process as a program running on your computer. Now each process has one or more threads. A game application might have a thread to load resources from disk, another to do AI, and another to run the game as a server.

一个应用程序中包含一个或多个进程。 可以将进程视为在计算机上运行的程序。 现在,每个进程都有一个或多个线程。 一个游戏应用程序可能具有一个线程来从磁盘加载资源,另一个可以执行AI,另一个可以作为服务器运行游戏。

In .NET/Windows, the operating system allocates processor time to a thread. Each thread keeps track of exception handlers and the priority at which it runs, and it has somewhere to save the thread context until it runs. Thread context is the information that the thread needs to resume.

在.NET / Windows中,操作系统将处理器时间分配给线程。 每个线程都会跟踪异常处理程序及其运行的优先级,并且在某个地方可以保存线程上下文,直到运行为止。 线程上下文是线程需要恢复的信息。

线程多任务 ( Multi-Tasking With Threads )

Threads take up a bit of memory and creating them takes a little time, so usually, you don't want to use many. Remember, they compete for processor time. If your computer has multiple CPUs, then Windows or .NET might run each thread on a different CPU, but if several threads run on the same CPU, then only one can be active at a time and switching threads takes time.

线程会占用一些内存,而创建它们会花费一些时间,因此通常不需要使用很多线程。 请记住,他们争夺处理器时间。 如果您的计算机有多个CPU,则Windows或.NET可能会在不同的CPU上运行每个线程,但是如果多个线程在同一CPU上运行,则一次只能激活一个线程,并且切换线程需要时间。

The CPU runs a thread for a few million instructions, and then it switches to another thread. All of the CPU registers, current program execution point and stack have to be saved somewhere for the first thread and then restored from somewhere else for the next thread.

CPU运行一个线程处理几百万条指令,然后切换到另一个线程。 所有CPU寄存器,当前程序执行点和堆栈都必须保存在第一个线程的某个位置,然后再从其他位置恢复以用于下一个线程。

创建一个线程 ( Creating a Thread )

In the namespace System. Threading, you'll find the thread type. The constructor thread (ThreadStart) creates an instance of a thread. However, in recent C# code, it's more likely to pass in a lambda expression that calls the method with any parameters.

在名称空间系统中。 Threading ,您将找到线程类型。 构造函数线程 (ThreadStart)创建线程的实例。 但是,在最近的C#代码中,更有可能传入一个lambda表达式,该表达式使用任何参数调用该方法。

If you're unsure about lambda expressions, it might be worth checking out LINQ.

如果不确定lambda表达式 ,则可能值得检查LINQ。

Here is an example of a thread that is created and started:

这是创建和启动的线程的示例:


using


using System.Threading;
namespace ex1
{
class Program
{
public static void Write1()
{
Console.Write('1') ;
Thread.Sleep(500) ;
}
static void Main(string[] args)
{
var task = new Thread(Write1) ;
task.Start() ;
for (var i = 0; i < 10; i++)
{
Console.Write('0') ;
Console.Write (task.IsAlive ? 'A' : 'D') ;
Thread.Sleep(150) ;
}
Console.ReadKey() ;
}

All this example does is write "1" to the console. The main thread writes a "0" to the console 10 times, each time followed by an "A" or "D" depending on whether the other thread is still Alive or Dead.

此示例所做的全部工作就是将“ 1”写入控制台。 主线程向控制台写入10次“ 0”,之后每次写入“ A”或“ D”,具体取决于另一个线程是“活动”还是“死亡”。

The other thread only runs once and writes a "1." After the half-second delay in the Write1() thread, the thread finishes, and the Task.IsAlive in the main loop now returns "D."

另一个线程仅运行一次并写入“ 1”。 在Write1()线程中延迟半秒之后,该线程结束,并且主循环中的Task.IsAlive现在返回“ D”。

线程池和任务并行库 ( Thread Pool and Task Parallel Library )

Instead of creating your own thread, unless you really need to do it, make use of a Thread Pool. From .NET 4.0, we have access to the Task Parallel Library (TPL). As in the previous example, again we need a bit of LINQ, and yes, it's all lambda expressions.

除非确实需要创建线程,否则不要使用自己的线程,而要使用线程池。 从.NET 4.0,我们可以访问任务并行库(TPL)。 与前面的示例一样,我们再次需要一些LINQ,是的,它们都是lambda表达式。

Tasks uses the Thread Pool behind the scenes but make better use of the threads depending on the number in use.

Tasks在后台使用线程池 ,但根据使用的数量更好地利用线程。

The main object in the TPL is a Task. This is a class that represents an asynchronous operation. The commonest way to start things running is with the Task.Factory.StartNew as in:

TPL中的主要对象是任务。 这是一个表示异步操作的类。 开始运行的最常见方法是使用Task.Factory.StartNew,如下所示:


Task.Factory.StartNew(() => DoSomet

Where DoSomething() is the method that is run. It's possible to create a task and not have it run immediately. In that case, just use Task like this:

其中DoSomething()是运行的方法。 可以创建一个任务,而不是立即运行它。 在这种情况下,只需使用像这样的Task:


var t = new Task(() => Console.WriteLine("Hello"));
...
t.

That doesn't start the thread until the .Start() is called. In the example below, are five tasks.

在调用.Start()之前,不会启动线程。 在下面的示例中,有五个任务。


using System;
using System.Threading;
using System.Threading.Tasks;
namespace ex1
{
class Program
{
public static void Write1(int i)
{
Console.Write(i) ;
Thread.Sleep(50) ;
}
static void Main(string[] args)
{
for (var i = 0; i < 5; i++)
{
var value = i;
var runningTask = Task.Factory.StartNew(()=>Write1(value)) ;
}
Console.ReadKey() ;
}

Run that and you get the digits 0 through 4 output in some random order such as 03214. That's because the order of task execution is determined by .NET.

运行该命令,您将以某种随机顺序(例如03214)获得数字0到4的输出。这是因为任务执行的顺序由.NET确定。

You might be wondering why the var value = i is needed. Try removing it and calling Write(i), and you'll see something unexpected like 55555. Why is this? It's because the task shows the value of i at the time that the task is executed, not when the task was created. By creating a new variable each time in the loop, each of the five values is correctly stored and picked up.

您可能想知道为什么需要var值= i。 尝试将其删除并调用Write(i),您会​​看到意外的东西,例如55555。这是为什么? 这是因为任务在执行任务时(而不是在创建任务时)显示i的值。 通过每次在循环中创建一个新变量 ,五个值中的每一个都可以正确存储和拾取。

翻译自: https://www.thoughtco.com/multi-threading-in-c-with-tasks-958372

c#中多线程与多任务区别

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值