C#使用Parallel類進(jìn)行多線程編程實(shí)例
更新時(shí)間:2015年06月16日 15:46:28 作者:紅薯
這篇文章主要介紹了C#使用Parallel類進(jìn)行多線程編程的方法,實(shí)例分析了Parallel類的相關(guān)使用技巧,需要的朋友可以參考下
本文實(shí)例講述了C#使用 Parallel 類進(jìn)行多線程編程的方法。分享給大家供大家參考。具體如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace Threads
{
class Program
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int GetCurrentProcessorNumber();
private static int criticalSection = 0;
private static object lockObject = new object();
static void Main(string[] args)
{
Console.WriteLine("==================Sequential calls==============");
Console.WriteLine();
Target();
Target();
Target();
Target();
Target();
Target();
Target();
Target();
Console.WriteLine();
Console.WriteLine("==================Parallel calls==============");
Console.WriteLine();
Action action = new Action(Target);
Parallel.Invoke(new Action[] { action, action, action, action, action, action, action, action });
Console.ReadKey();
}
private static void Target()
{
Thread.Sleep(2000);
lock (lockObject)
{
criticalSection++;
Console.WriteLine(string.Format("Thread ID: {0} and Processor ID: " +
"{1} Critical Variable Value: {2}",
Thread.CurrentThread.ManagedThreadId,
GetCurrentProcessorNumber(), criticalSection));
}
}
}
}
希望本文所述對(duì)大家的C#程序設(shè)計(jì)有所幫助。
相關(guān)文章
C#實(shí)現(xiàn)漢字轉(zhuǎn)區(qū)位碼的示例代碼
區(qū)位碼是一個(gè)4位的十進(jìn)制數(shù),每個(gè)區(qū)位碼都對(duì)應(yīng)著一個(gè)唯一的漢字,區(qū)位碼的前兩位叫做區(qū)碼,后兩位叫做位碼,下面我們就來看看如何使用C#實(shí)現(xiàn)漢字轉(zhuǎn)區(qū)位碼吧2024-01-01
Unity實(shí)現(xiàn)滑動(dòng)更換界面效果
這篇文章主要為大家詳細(xì)介紹了Unity實(shí)現(xiàn)滑動(dòng)更換界面效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-07-07
C#中DataSet轉(zhuǎn)化為實(shí)體集合類的方法
這篇文章主要介紹了C#中DataSet轉(zhuǎn)化為實(shí)體集合類的方法,是非常實(shí)用的技巧,需要的朋友可以參考下2014-10-10
解析abstract與override究竟可不可以同時(shí)使用
本篇文章是對(duì)abstract與override究竟可不可以同時(shí)使用進(jìn)行了詳細(xì)分析介紹,需要的朋友參考下2013-05-05
C#設(shè)計(jì)模式之Facade外觀模式解決天河城購物問題示例
這篇文章主要介紹了C#設(shè)計(jì)模式之Facade外觀模式解決天河城購物問題,簡單描述了外觀模式的定義并結(jié)合具體實(shí)例分析了外觀模式解決購物問題的相關(guān)步驟與操作技巧,需要的朋友可以參考下2017-09-09
C#設(shè)計(jì)模式實(shí)現(xiàn)之迭代器模式
迭代器模式把對(duì)象的職責(zé)分離,職責(zé)分離可以最大限度減少彼此之間的耦合程度,從而建立一個(gè)松耦合的對(duì)象,這篇文章主要給大家介紹了關(guān)于C#設(shè)計(jì)模式實(shí)現(xiàn)之迭代器模式的相關(guān)資料,需要的朋友可以參考下2021-08-08
unity實(shí)現(xiàn)動(dòng)態(tài)排行榜
這篇文章主要為大家詳細(xì)介紹了unity實(shí)現(xiàn)動(dòng)態(tài)排行榜,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-07-07

