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#讀取XML的CDATA節(jié)點(diǎn)內(nèi)容實(shí)例詳解
在本篇文章里小編給大家整理了關(guān)于C# 讀取XML的CDATA節(jié)點(diǎn)內(nèi)容的相關(guān)知識(shí)點(diǎn)內(nèi)容,有需要的朋友們參考學(xué)習(xí)下。2019-09-09
詳解C#如何解決程序卡頓的問題(多線程初步學(xué)習(xí))
在編寫程序的時(shí)候,有時(shí)候難免會(huì)出現(xiàn)后臺(tái)運(yùn)行時(shí)間過長(zhǎng)的問題,這個(gè)時(shí)候就要考慮多線程的操作了,所以本文給大家介紹了C#解決程序卡頓問題的方法,需要的朋友可以參考下2024-04-04
C# 關(guān)于爬取網(wǎng)站數(shù)據(jù)遇到csrf-token的分析與解決
這篇文章主要介紹了C# 關(guān)于爬取網(wǎng)站數(shù)據(jù)遇到csrf-token的分析與解決,幫助大家更好的理解和學(xué)習(xí)c#,感興趣的朋友可以了解下2021-01-01
WPF實(shí)現(xiàn)類似ChatGPT逐字打印效果的示例代碼
前一段時(shí)間ChatGPT類的應(yīng)用十分火爆,這類應(yīng)用在回答用戶的問題時(shí)逐字打印輸出,像極了真人打字回復(fù)消息,本文就來利用WPF模擬一下這種逐字打印的效果吧2023-08-08
C#獲取ListView鼠標(biāo)下的Item實(shí)例
下面小編就為大家?guī)硪黄狢#獲取ListView鼠標(biāo)下的Item實(shí)例。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-01-01

