Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

Task.Run: practical reference

Task.Run: practical reference: Task.Run queues a delegate to the thread pool and returns a Task for its execution.

Version: .NET API; verified against .NET 10 reference surface

Syntax

Task.Run(/* overload-specific arguments */)

Task.Run queues a delegate to the thread pool and returns a Task for its execution.

Use it for CPU-bound work off a UI thread, not to wrap naturally asynchronous I/O.

Canceling the token does not stop an already running delegate without cooperation.

Exceptions are stored in the Task; async overloads unwrap the inner Task.

The complete program actually uses Task.Run; its exact expected stdout is 42.

Examples

using System;
using System.Buffers;
using System.Collections.Concurrent;
using System.Collections.Frozen;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Number = System.Int32;

var task = Task.Run(() => 6 * 7);
Console.WriteLine(await task);

Result

42

The complete program actually uses `Task.Run`; its exact expected stdout is `42`.

Sources