.NET/C#
  • ASP.NET Core Overview
  • ASP.NET Core API tutorial
    • How to create ASP.NET Core C# API tutorial
      • launchSettings
      • Install swagger
        • Swagger best practices
      • Run the app
      • Fix CORS problem
      • Add AutoMapper
      • Add JWT reference
      • Add .gitignore
      • Basic structure & EF Core
      • AddSingleton
    • Loading Related Entities
  • Unit test controller logic in ASP.NET Core
    • Unit testing controllers
  • .NET Q&A
    • dotnet try
    • LINQ
      • LINQ Query Syntax
      • Lambda Expression
      • Standard Query Operators
  • .NET C# Interview questions
    • C# - .NET interview questions and answers [Part 1]
    • C# - .NET interview questions and answers [Part 2]
    • C# Interview questions [Part 3] General questions
  • C#
    • Object-Oriented Programming (Principles)
      • N-tier architecture style
      • Command and Query Responsibility Segregation (CQRS) pattern
      • Project architecture
    • C# Advanced review
      • Implicit typing
      • Generics
      • Attributes
      • Reflection
      • Delegates
      • Anonymous Methods and Lambda Expressions
      • Events
      • Ref vs Out
      • Task
        • TaskFactory Class
  • MySQL
    • MySQL Lerning
      • SELECT
      • ORDER BY
      • WHERE
      • DISTINCT
      • IN
      • BETWEEN
      • Join
      • INNER JOIN
      • LEFT JOIN
      • RIGHT JOIN
      • GROUP BY
      • Subquery
      • UNION
    • Stored Procedures
      • CREATE PROCEDURE
  • Versioning API, MongoDB and ci-cd
    • Create a web API with ASP.NET Core and MongoDB
    • REST API versioning with ASP.NET Core
    • Design a CI/CD pipeline using Azure DevOps
      • Create a CI/CD pipeline for GitHub repo using Azure DevOps Starter
  • TFS & TFCV
    • What is Team Foundation Version Control
      • Develop and share your code in TFVC using Visual Studio
      • Suspend your work and manage your shelvesets
    • Newtonsoft Json.NET
      • Serializing and Deserializing JSON
  • MS-SQL
    • Quick tutorial
      • Add new column to a table
      • LEFT/RIGHT Reverse operator
      • Dates (Transact-SQL)
      • CAST and CONVERT (Transact-SQL)
      • Types of JOIN
      • Our first Left Outer Join
      • CROSS JOIN
Powered by GitBook
On this page
  • Examples
  • ContinueWith(Action<Task>)

Was this helpful?

  1. C#
  2. C# Advanced review
  3. Task

TaskFactory Class

PreviousTaskNextMySQL Lerning

Last updated 4 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