詳細介紹.NET並行與多線程學習基礎

來源:互聯網
上載者:User
一、並行初試:

public static void test()        {            for (int i = 0; i < 10000; i++)            {                Console.WriteLine(i);            }        }        public static void test1()        {            for (int i = 0; i < 10000; i++)            {                Console.WriteLine(i + "aaaaaaaaaaaaaaa");            }        }

調用:

static void Main(string[] args)        {            Stopwatch sw = new Stopwatch();            sw.Start();//串列執行:test();test1();//並存執行:17Parallel.Invoke(test, test1);19sw.Stop();21Console.WriteLine("共耗費時間:");23Console.WriteLine(sw.ElapsedMilliseconds / 1000+"s");}

二、分區並行:

Parallel.ForEach(Partitioner.Create(1,20,5),(x,s)=>{                //並行代碼中自訂串列,第三個參數表示item1到item2之間的範圍                Console.WriteLine(x);                for (int i = x.Item1; i < x.Item2; i++)                {                    if (i == 10) break;                    Console.WriteLine(i);                }                s.Break();// 非常類似普通for迴圈中的break                if (s.ShouldExitCurrentIteration)                    return;            });

三、異常捕獲:AggregateException

int[] arry = new int[10001];            for (int i = 0; i < 10000; i++)            {                arry[i] = i;            }            try            {                Parallel.ForEach(arry, (x, s) =>                {                    Console.WriteLine(x);                    if (sw.Elapsed.Seconds > 3)                    {                        throw new TimeoutException("操作逾時");                    }                });            }            catch (AggregateException ex)            {                foreach (var item in ex.InnerExceptions)                {                    Console.WriteLine(item);                }            }

四、指定並行調度:

ParallelOptions options = new ParallelOptions();            options.MaxDegreeOfParallelism = 1;//如果設定為1就類似於串列代碼按順序執行            options.MaxDegreeOfParallelism =Environment.ProcessorCount;//擷取電腦上面的處理器數量            Parallel.For(1,10,options,(x) =>            {                Console.WriteLine(x);            });
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.