等待一个或多个任务完成--NET并行

原文地址:http://msdn.microsoft.com/zh-cn/library/dd537610(v=vs.110).aspx

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Net;

namespace TPL
{
    public class ParallelTask
    {
        #region 等待任务执行完毕

        public static void WaitTaskComplete()
        {
            // 无时间限制等待任务完成没有
            Task taskA = Task.Factory.StartNew(() => ParallelTask.DoSomeWork(10000000));
            taskA.Wait();

            // 规定时间内等待任务完成
            Task taskB = Task.Factory.StartNew(() => ParallelTask.DoSomeWork(10000000));
            taskB.Wait(100);

            // 等待所有任务完成
            Task[] tasks = new Task[10];
            for (int i = 0; i < 10; i++)
            {
                tasks[i] = Task.Factory.StartNew(() => ParallelTask.DoSomeWork(10000000));
            }
            Task.WaitAll(tasks);

            // 等待第一个任务完成
            Task<double>[] tasks2 = new Task<double>[3];
            tasks2[0] = Task<double>.Factory.StartNew(() => ParallelTask.TrySolution1());
            tasks2[1] = Task<double>.Factory.StartNew(() => ParallelTask.TrySolution2());
            tasks2[2] = Task<double>.Factory.StartNew(() => ParallelTask.TrySolution3());
           
            // 最先完成任务的索引和结果
            int index = Task.WaitAny(tasks2);
            double d = tasks2[index].Result;
        }

        private static void DoSomeWork(int val)
        {
            Thread.SpinWait(val);
        }

        private static double TrySolution1()
        {
            Random rand = new Random();
            int i = rand.Next(1000000);
            Thread.SpinWait(i);
            return DateTime.Now.Millisecond;
        }

        private static double TrySolution2()
        {
            Random rand = new Random();
            int i = rand.Next(1000000);
            Thread.SpinWait(i);
            return DateTime.Now.Millisecond;
        }

        private static double TrySolution3()
        {
            Random rand = new Random();
            int i = rand.Next(1000000);
            Thread.SpinWait(i);
            Thread.SpinWait(1000000);
            return DateTime.Now.Millisecond;
        }

        #endregion

        #region Invoke方法执行操作

        public static void ParallelInvoke()
        {
            string[] words = CreateWordArray(@"http://www.gutenberg.org/files/2009/2009.txt");

            // Perform three tasks in parallel on the source array
            Parallel.Invoke(() =>
            {
                GetLongestWord(words);
            },  // close first Action
            () =>
            {
                GetMostCommonWords(words);
            }, //close second Action
            () =>
            {
                GetCountForWord(words, "species");
            } //close third Action
            ); //close parallel.invoke


        }

        private static void GetCountForWord(string[] words, string term)
        {
            var findWord = from word in words
                           where word.ToUpper().Contains(term.ToUpper())
                           select word;
        }

        private static void GetMostCommonWords(string[] words)
        {
            var frequencyOrder = from word in words
                                 where word.Length > 6
                                 group word by word into g
                                 orderby g.Count() descending
                                 select g.Key;

            var commonWords = frequencyOrder.Take(10);

            StringBuilder sb = new StringBuilder();
            sb.AppendLine("Task 2 -- The most common words are:");
            foreach (var v in commonWords)
            {
                sb.AppendLine("  " + v);
            }
        }

        private static string GetLongestWord(string[] words)
        {
            var longestWord = (from w in words
                               orderby w.Length descending
                               select w).First();

            return longestWord;
        }

        static string[] CreateWordArray(string uri)
        {
            string s = new WebClient().DownloadString(uri);

            return s.Split(new char[] { ' ', '\u000A', ',', '.', ';', ':', '-', '_', '/' },
                StringSplitOptions.RemoveEmptyEntries);
        }

        #endregion
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值