[英]How to spawn thread in C#
Could anyone please give a sample or any link that describes how to spawn thread where each will do different work at the same time.任何人都可以提供一个示例或任何链接来描述如何生成线程,每个线程将同时执行不同的工作。
Suppose I have job1 and job2.假设我有 job1 和 job2。 I want to run both the jobs simultaneously.我想同时运行这两个作业。 I need those jobs to get executed in parallel.我需要并行执行这些作业。 how can I do that?我怎样才能做到这一点?
Well, fundamentally it's as simple as:嗯,从根本上说它很简单:
ThreadStart work = NameOfMethodToCall;
Thread thread = new Thread(work);
thread.Start();
...
private void NameOfMethodToCall()
{
// This will be executed on another thread
}
However, there are other options such as the thread pool or (in .NET 4) using Parallel Extensions.但是,还有其他选项,例如线程池或(在 .NET 4 中)使用并行扩展。
I have a threading tutorial which is rather old, and Joe Alabahari has one too .我有一个很旧的线程教程, Joe Alabahari 也有一个。
Threading Tutorial from MSDN!来自 MSDN 的线程教程!
http://msdn.microsoft.com/en-us/library/aa645740(VS.71).aspxhttp://msdn.microsoft.com/en-us/library/aa645740(VS.71).aspx
Threads in C# are modelled by Thread Class. C# 中的线程由 Thread 类建模。 When a process starts (you run a program) you get a single thread (also known as the main thread) to run your application code.当一个进程启动(你运行一个程序)时,你会得到一个线程(也称为主线程)来运行你的应用程序代码。 To explicitly start another thread (other than your application main thread) you have to create an instance of thread class and call its start method to run the thread using C#, Let's see an example要显式启动另一个线程(应用程序主线程除外),您必须创建线程类的实例并调用其 start 方法以使用 C# 运行线程,让我们看一个示例
using System;
using System.Diagnostics;
using System.Threading;
public class Example
{
public static void Main()
{
//initialize a thread class object
//And pass your custom method name to the constructor parameter
Thread thread = new Thread(SomeMethod);
//start running your thread
thread.Start();
Console.WriteLine("Press Enter to terminate!");
Console.ReadLine();
}
private static void SomeMethod()
{
//your code here that you want to run parallel
//most of the cases it will be a CPU bound operation
Console.WriteLine("Hello World!");
}
}
You can learn more in this tutorial Multithreading in C# , Here you will learn how to take advantage of Thread class and Task Parallel Library provided by C# and .NET Framework to create robust applications that are responsive, parallel and meet the user expectations.您可以在本教程C# 中的多线程中了解更多信息,在这里您将学习如何利用 C# 和 .NET Framework 提供的线程类和任务并行库来创建响应式、并行并满足用户期望的健壮应用程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.