.NET Course
  • Welcome developers
  • LINQ
    • Advanced c# overview
      • Implicit typing
      • Generics
      • Attributes
      • Reflection
      • Delegates
      • Anonymous Methods and Lambda Expressions
      • Events
      • Anonymous Types
      • Ref vs Out
      • Task
      • TaskFactory
      • Asynchronous programming with async and await
      • Abstract class VS Interface
      • Inheritance, Composition and Aggregation in C#
    • LINQ Tutorial
      • Loading Related Entities
      • Lambda Expression
      • Standard Query Operators
    • Testing ASP.NET Core
      • Implementing unit tests for ASP.NET Core Web APIs
    • Software development principles
      • Object-Oriented Programming (Principles)
      • N-tier architecture style
      • Command and Query Responsibility Segregation (CQRS) pattern
      • SOLID: The First 5 Principles of Object Oriented Design
  • Helping links
    • SonarQube installation and tutorial for .net core projects
  • C# .NET Interview Questions
    • Ultimate C# Interview questions
      • Part 4
      • Part 3
      • Part 2
      • Part 1
  • Unit test .NET Core xUnit & MOQ
    • Content
      • Snippets
      • Traits
Powered by GitBook
On this page
  • Examples
  • ContinueWith(Action<Task>)

Was this helpful?

  1. LINQ
  2. Advanced c# overview

TaskFactory

PreviousTaskNextAsynchronous programming with async and await

Last updated 3 years ago

Was this helpful?

Provides support for creating and scheduling objects.

public class TaskFactory

Examples

The following example uses the static property to make two calls to the method. The first populates an array with the names of files in the user's MyDocuments directory, while the second populates an array with the names of subdirectories of the user's MyDocuments directory. It then calls the method, which displays information about the number of files and directories in the two arrays after the first two tasks have completed execution.

using System;
using System.IO;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      Task[] tasks = new Task[2];
      String[] files = null;
      String[] dirs = null;
      String docsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

      tasks[0] = Task.Factory.StartNew( () => files = Directory.GetFiles(docsDirectory));
      tasks[1] = Task.Factory.StartNew( () => dirs = Directory.GetDirectories(docsDirectory));

      Task.Factory.ContinueWhenAll(tasks, completedTasks => {
                                             Console.WriteLine("{0} contains: ", docsDirectory);
                                             Console.WriteLine("   {0} subdirectories", dirs.Length);
                                             Console.WriteLine("   {0} files", files.Length);
                                          } );
   }
}
// The example displays output like the following:
//       C:\Users\<username>\Documents contains:
//          24 subdirectories
//          16 files

Let's take a look at the following piece of code:

static void Main(string[] args)
{
    /// This guy will be initialized immediately
    /// So we do not actually need the .Start() to initialize the Task
    /// It will do it automatically.
    var t1 = Task.Factory.StartNew(() => DoSomethingImportantWork(1, 1500));

    var t2 = new Task(() => DoSomethingImportantWork(2, 3000));
    t2.Start();

    var t3 = new Task(() => DoSomethingImportantWork(3, 1000));
    t3.Start();

    Console.WriteLine("Press any key to quit");
    Console.ReadLine();
}

static void DoSomethingImportantWork(int id, int sleepTime)
{
    Console.WriteLine("Task {0} is beginning", id);
    Thread.Sleep(sleepTime);
    Console.WriteLine("Task {0} has completed", id);
}

ContinueWith(Action<Task>)

/// This guy will be initialized immediately
/// So we do not actually need the .Start() to initialize the Task
/// It will do it automatically.
var t1 = Task.Factory.StartNew(() => DoSomethingImportantWork(1, 1500))
    .ContinueWith((prevTask) => DoSomeOtherImportantWork(1, 1000));
// Press any key to quit
// Task 2 is beginning
// Task 1 is beginning
// Task 3 is beginning
// Task 3 has completed
// Task 1 has completed
// Task 1 is beginning ===> here is our ContinueWith
// Task 1 has completed
// Task 2 has completed

Creates a continuation that executes asynchronously when the target completes.

Task
Factory
TaskFactory.StartNew
TaskFactory.ContinueWhenAll(Task[], Action<Task[]>)
Task