当前位置: 首页>>代码示例>>C#>>正文


C# Task.Run方法代码示例

本文整理汇总了C#中System.Threading.Tasks.Task.Run方法的典型用法代码示例。如果您正苦于以下问题:C# Task.Run方法的具体用法?C# Task.Run怎么用?C# Task.Run使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Threading.Tasks.Task的用法示例。


在下文中一共展示了Task.Run方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Main

//引入命名空间
using System;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      ShowThreadInfo("Application");

      var t = Task.Run(() => ShowThreadInfo("Task") );
      t.Wait();
   }

   static void ShowThreadInfo(String s)
   {
      Console.WriteLine("{0} Thread ID: {1}",
                        s, Thread.CurrentThread.ManagedThreadId);
   }
}
开发者ID:.NET开发者,项目名称:System.Threading.Tasks,代码行数:21,代码来源:Task.Run

输出:

Application thread ID: 1
Task thread ID: 3

示例2: Main

//引入命名空间
using System;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      Console.WriteLine("Application thread ID: {0}",
                        Thread.CurrentThread.ManagedThreadId);
      var t = Task.Run(() => {  Console.WriteLine("Task thread ID: {0}",
                                   Thread.CurrentThread.ManagedThreadId);
                             } );
      t.Wait();
   }
}
开发者ID:.NET开发者,项目名称:System.Threading.Tasks,代码行数:17,代码来源:Task.Run

输出:

Application thread ID: 1
Task thread ID: 3

示例3: Main

//引入命名空间
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      var list = new ConcurrentBag<string>();
      string[] dirNames = { ".", ".." };
      List<Task> tasks = new List<Task>();
      foreach (var dirName in dirNames) {
         Task t = Task.Run( () => { foreach(var path in Directory.GetFiles(dirName)) 
                                       list.Add(path); }  );
         tasks.Add(t);
      }
      Task.WaitAll(tasks.ToArray());
      foreach (Task t in tasks)
         Console.WriteLine("Task {0} Status: {1}", t.Id, t.Status);
         
      Console.WriteLine("Number of files read: {0}", list.Count);
   }
}
开发者ID:.NET开发者,项目名称:System.Threading.Tasks,代码行数:26,代码来源:Task.Run

输出:

Task 1 Status: RanToCompletion
Task 2 Status: RanToCompletion
Number of files read: 23

示例4: Main

//引入命名空间
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static async Task Main()
   {
      var tokenSource = new CancellationTokenSource();
      var token = tokenSource.Token;
      var files = new List<Tuple<string, string, long, DateTime>>();

      var t = Task.Run( () => { string dir = "C:\\Windows\\System32\\";
                                object obj = new Object();
                                if (Directory.Exists(dir)) {
                                   Parallel.ForEach(Directory.GetFiles(dir),
                                   f => {
                                           if (token.IsCancellationRequested)
                                              token.ThrowIfCancellationRequested();
                                           var fi = new FileInfo(f);
                                           lock(obj) {
                                              files.Add(Tuple.Create(fi.Name, fi.DirectoryName, fi.Length, fi.LastWriteTimeUtc));          
                                           }
                                      });
                                 }
                              }
                        , token);
      await Task.Yield();
      tokenSource.Cancel();
      try {
         await t;
         Console.WriteLine("Retrieved information for {0} files.", files.Count);
      }
      catch (AggregateException e) {
         Console.WriteLine("Exception messages:");
         foreach (var ie in e.InnerExceptions)
            Console.WriteLine("   {0}: {1}", ie.GetType().Name, ie.Message);

         Console.WriteLine("\nTask status: {0}", t.Status);       
      }
      finally {
         tokenSource.Dispose();
      }
   }
}
开发者ID:.NET开发者,项目名称:System.Threading.Tasks,代码行数:48,代码来源:Task.Run

输出:

Exception messages:
TaskCanceledException: A task was canceled.
TaskCanceledException: A task was canceled.
...

Task status: Canceled

示例5: Main

//引入命名空间
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      var tasks = new List<Task<int>>();
      var source = new CancellationTokenSource();
      var token = source.Token;
      int completedIterations = 0;

      for (int n = 0; n <= 19; n++)
         tasks.Add(Task.Run( () => { int iterations = 0;
                                     for (int ctr = 1; ctr <= 2000000; ctr++) {
                                         token.ThrowIfCancellationRequested();
                                         iterations++;
                                     }
                                     Interlocked.Increment(ref completedIterations);
                                     if (completedIterations >= 10)
                                        source.Cancel();
                                     return iterations; }, token));

      Console.WriteLine("Waiting for the first 10 tasks to complete...\n");
      try  {
         Task.WaitAll(tasks.ToArray());
      }
      catch (AggregateException) {
         Console.WriteLine("Status of tasks:\n");
         Console.WriteLine("{0,10} {1,20} {2,14:N0}", "Task Id",
                           "Status", "Iterations");
         foreach (var t in tasks)
            Console.WriteLine("{0,10} {1,20} {2,14}",
                              t.Id, t.Status,
                              t.Status != TaskStatus.Canceled ? t.Result.ToString("N0") : "n/a");
      }
   }
}
开发者ID:.NET开发者,项目名称:System.Threading.Tasks,代码行数:41,代码来源:Task.Run

输出:

Waiting for the first 10 tasks to complete...
Status of tasks:

Task Id               Status     Iterations
1      RanToCompletion      2,000,000
2      RanToCompletion      2,000,000
3      RanToCompletion      2,000,000
4      RanToCompletion      2,000,000
5      RanToCompletion      2,000,000
6      RanToCompletion      2,000,000
7      RanToCompletion      2,000,000
8      RanToCompletion      2,000,000
9      RanToCompletion      2,000,000
10             Canceled            n/a
11             Canceled            n/a
12             Canceled            n/a
13             Canceled            n/a
14             Canceled            n/a
15             Canceled            n/a
16      RanToCompletion      2,000,000
17             Canceled            n/a
18             Canceled            n/a
19             Canceled            n/a
20             Canceled            n/a

示例6: Main

//引入命名空间
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      var tasks = new List<Task<int>>();
      var source = new CancellationTokenSource();
      var token = source.Token;
      int completedIterations = 0;

      for (int n = 0; n <= 19; n++)
         tasks.Add(Task.Run( () => { int iterations = 0;
                                     for (int ctr = 1; ctr <= 2000000; ctr++) {
                                         if (token.IsCancellationRequested)
                                            return iterations;
                                         iterations++;
                                     }
                                     Interlocked.Increment(ref completedIterations);
                                     if (completedIterations >= 10)
                                        source.Cancel();
                                     return iterations; }, token));

      Console.WriteLine("Waiting for the first 10 tasks to complete...\n");
      try  {
         Task.WaitAll(tasks.ToArray());
      }
      catch (AggregateException) {
         Console.WriteLine("Status of tasks:\n");
         Console.WriteLine("{0,10} {1,20} {2,14:N0}", "Task Id",
                           "Status", "Iterations");
         foreach (var t in tasks)
            Console.WriteLine("{0,10} {1,20} {2,14}",
                              t.Id, t.Status,
                              t.Status != TaskStatus.Canceled ? t.Result.ToString("N0") : "n/a");
      }
   }
}
开发者ID:.NET开发者,项目名称:System.Threading.Tasks,代码行数:42,代码来源:Task.Run

输出:

Status of tasks:

Task Id               Status     Iterations
1      RanToCompletion      2,000,000
2      RanToCompletion      2,000,000
3      RanToCompletion      2,000,000
4      RanToCompletion      2,000,000
5      RanToCompletion      2,000,000
6      RanToCompletion      2,000,000
7      RanToCompletion      2,000,000
8      RanToCompletion      2,000,000
9      RanToCompletion      2,000,000
10      RanToCompletion      1,658,326
11      RanToCompletion      1,988,506
12      RanToCompletion      2,000,000
13      RanToCompletion      1,942,246
14      RanToCompletion        950,108
15      RanToCompletion      1,837,832
16      RanToCompletion      1,687,182
17      RanToCompletion        194,548
18             Canceled    Not Started
19             Canceled    Not Started
20             Canceled    Not Started

示例7: Main

//引入命名空间
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      string pattern = @"\p{P}*\s+";
      string[] titles = { "Sister Carrie", "The Financier" };
      Task<int>[] tasks = new Task<int>[titles.Length];

      for (int ctr = 0; ctr < titles.Length; ctr++) {
         string s = titles[ctr];
         tasks[ctr] = Task.Run( () => {
                                   // Number of words.
                                   int nWords = 0;
                                   // Create filename from title.
                                   string fn = s + ".txt";
                                   if (File.Exists(fn)) {
                                      StreamReader sr = new StreamReader(fn);
                                      string input = sr.ReadToEndAsync().Result;
                                      nWords = Regex.Matches(input, pattern).Count;
                                   }
                                   return nWords;
                                } );
      }
      Task.WaitAll(tasks);

      Console.WriteLine("Word Counts:\n");
      for (int ctr = 0; ctr < titles.Length; ctr++)
         Console.WriteLine("{0}: {1,10:N0} words", titles[ctr], tasks[ctr].Result);
   }
}
开发者ID:.NET开发者,项目名称:System.Threading.Tasks,代码行数:36,代码来源:Task.Run

输出:

Sister Carrie:    159,374 words
The Financier:    196,362 words


注:本文中的System.Threading.Tasks.Task.Run方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。