百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
S

sdk-dotnet

> 编程语言
开源

Temporal .NET SDK

563 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

Temporal .NET SDK

Temporal is a distributed, scalable, durable, and highly available orchestration engine used to execute asynchronous, long-running business logic in a scalable and resilient way.

"Temporal .NET SDK" is the framework for authoring workflows and activities using .NET programming languages.

Also see:

  • Application Development Guide
  • .NET Samples
  • API Documentation

Extensions:

  • Temporalio.Extensions.DiagnosticSource - System.Diagnostics.Metrics support for SDK metrics
  • Temporalio.Extensions.Hosting - Client dependency injection, activity dependency injection, and worker generic host support
  • Temporalio.Extensions.OpenTelemetry - OpenTelemetry tracing support
  • Temporalio.Extensions.WorkflowStreams - experimental durable, offset-based workflow publish/subscribe streams

Contents

  • Quick Start
    • Installation
    • Implementing a Workflow and Activity
    • Running a Worker
    • Executing a Workflow
  • Usage
    • Clients
      • Cloud Client Using MTLS
      • Client Dependency Injection
      • Data Conversion
    • Workers
      • Worker as Generic Host
    • Workflows
      • Workflow Definition
        • Workflow Inheritance
      • Running Workflows
      • Invoking Activities
      • Invoking Child Workflows
      • Invoking Nexus Operations
      • Timers and Conditions
      • Workflow Task Scheduling and Cancellation
      • Workflow Utilities
      • Workflow Exceptions
      • Workflow Logic Constraints
        • .NET Task Determinism
        • Workflow .editorconfig
      • Workflow Testing
        • Automatic Time Skipping
        • Manual Time Skipping
        • Mocking Activities
      • Workflow Replay
    • Activities
      • Activity Definition
      • Activity Dependency Injection
      • Activity Execution Context
      • Activity Heartbeating and Cancellation
      • Activity Worker Shutdown
      • Invoking Standalone Activities
      • Activity Testing
    • Nexus
      • Nexus Operations Backed by Workflows
    • OpenTelemetry Tracing Support
    • Built-in Native Shared Library
    • TLS/CA Loading Issues
      • AWS Lambda .NET CA Loading Issues
      • Azure App Service CA Loading Issues
  • Development
    • Build
    • Code formatting
      • VisualStudio Code
    • Testing
    • Regenerating code
    • Regenerating API docs

Quick Start

Installation

Add the Temporalio package from NuGet. For example, using the dotnet CLI:

dotnet add package Temporalio

The .NET SDK supports .NET Framework >= 4.6.2, .NET Core >= 3.1 (so includes .NET 5+), and .NET Standard >= 2.0. If you are using .NET Framework or a non-standard target platform, see the Built-in Native Shared Library section later for additional information.

NOTE: This README is for the current branch and not necessarily what's released on NuGet.

Implementing a Workflow and Activity

Assuming the ImplicitUsings is enabled, create an activity by putting the following in MyActivities.cs:

csharp
namespace MyNamespace;

using Temporalio.Activities;

public class MyActivities
{
    // Activities can be async and/or static too! We just demonstrate instance
    // methods since many will use them that way.
    [Activity]
    public string SayHello(string name) => $"Hello, {name}!";
}

That creates the activity. Now to create the workflow, put the following in SayHelloWorkflow.workflow.cs:

…

This is a simple workflow that executes the SayHello activity.

Running a Worker

To run this in a worker, put the following in Program.cs:

…

When executed, this will listen for Temporal server requests to perform workflow and activity invocations.

Executing a Workflow

To start and wait on a workflow result, with the worker program running elsewhere, put the following in a different project's Program.cs that references the worker project:

csharp
using MyNamespace;
using Temporalio.Client;

// Create a client to localhost on "default" namespace
var client = await TemporalClient.ConnectAsync(new("localhost:7233"));

// Run workflow
var result = await client.ExecuteWorkflowAsync(
    (SayHelloWorkflow wf) => wf.RunAsync("Temporal"),
    new(id: "my-workflow-id", taskQueue: "my-task-queue"));

Console.WriteLine("Workflow result: {0}", result);

This will output:

Workflow result: Hello, Temporal!

Usage

Clients

A client can be created and used to start a workflow. For example:

csharp
using MyNamespace;
using Temporalio.Client;

// Create client connected to server at the given address and namespace
var client = await TemporalClient.ConnectAsync(new()
{
    TargetHost = "localhost:7233",
    Namespace = "my-namespace",
});

// Start a workflow
var handle = await client.StartWorkflowAsync(
    (MyWorkflow wf) => wf.RunAsync("some workflow argument"),
    new() { ID = "my-workflow-id", TaskQueue = "my-task-queue" });

// Wait for a result
var result = await handle.GetResultAsync();
Console.WriteLine("Result: {0}", result);

Notes about the above code:

  • Temporal clients are not explicitly disposable.
  • To enable TLS, the Tls option can be set to a non-null TlsOptions instance.
  • Instead of StartWorkflowAsync + GetResultAsync above, there is an ExecuteWorkflowAsync extension method that is clearer if the handle is not needed.
  • The type-safe forms of StartWorkflowAsync and ExecuteWorkflowAsync accept a lambda expression that take the workflow as the first parameter and must only call the run method in the lambda.
  • Non-type-safe forms of StartWorkflowAsync and ExecuteWorkflowAsync exist when there is no workflow definition or the workflow may take more than one argument or some other dynamic need. These simply take string workflow type names and an object array for arguments.
  • The handle above represents a WorkflowHandle which has specific workflow operations on it. For existing workflows, handles can be obtained via client.GetWorkflowHandle.

Cloud Client Using MTLS

Assuming a client certificate is present at my-cert.pem and a client key is present at my-key.pem, this is how to connect to Temporal Cloud:

csharp
using Temporalio.Client;

var client = await TemporalClient.ConnectAsync(new("my-namespace.a1b2c.tmprl.cloud:7233")
{
    Namespace = "my-namespace.a1b2c",
    Tls = new()
    {
        ClientCert = await File.ReadAllBytesAsync("my-cert.pem"),
        ClientPrivateKey = await File.ReadAllBytesAsync("my-key.pem"),
    },
});

Client Configuration From Environment

Client connection options can be loaded from a temporal.toml file and environment variables:

csharp
using Temporalio.Client;
using Temporalio.Common.EnvConfig;

var client = await TemporalClient.ConnectAsync(
    ClientEnvConfig.LoadClientConnectOptions());

By default, the loader checks TEMPORAL_CONFIG_FILE; if unset, it looks for temporal.toml in the user config directory under temporalio. If no file exists at the discovered or specified path, the loader still succeeds using default connection options plus any environment variable overrides. The selected profile is TEMPORAL_PROFILE, or default when unset. Supported environment variables override file values; see Temporal environment configuration for the complete list.

Use ClientEnvConfig.ProfileLoadOptions to choose a profile, provide an explicit config source, or disable file or environment loading.

Client Dependency Injection

To create clients for use with dependency injection, see the Temporalio.Extensions.Hosting project which has extension methods for creating singleton clients lazily on service collections.

For manually creating clients for dependency injection, users may prefer TemporalClient.CreateLazy which is a synchronous method which creates a client that does not attempt to connect until the first call is made on it. This can be helpful for dependency injection but beware that deferring connection until later can make it hard to see issues with connection parameters as early as may be expected. However, connection must be made before a worker is created with it.

Data Conversion

Data converters are used to convert raw Temporal payloads to/from actual .NET types. A custom data converter can be set via the DataConverter option when creating a client. Data converters are a combination of payload converters, payload codecs, and failure converters. Payload converters convert .NET values to/from serialized bytes. Payload codecs convert bytes to bytes (e.g. for compression or encryption). Failure converters convert exceptions to/from serialized failures.

Data converters are in the Temporalio.Converters namespace. The default data converter uses a default payload converter, which supports the following types:

  • null
  • byte[]
  • Google.Protobuf.IMessage instances
  • Anything that System.Text.Json supports
  • IRawValue as unconverted raw payloads

Custom converters can be created for all uses. For example, to create client with a data converter that converts all C# property names to camel case, you would:

csharp
using System.Text.Json;
using Temporalio.Client;
using Temporalio.Converters;

public class CamelCasePayloadConverter : DefaultPayloadConverter
{
    public CamelCasePayloadConverter()
        : base(new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase })
    {
    }
}

var client = await TemporalClient.ConnectAsync(new()
{
    TargetHost = "localhost:7233",
    Namespace = "my-namespace",
    DataConverter = DataConverter.Default with { PayloadConverter = new CamelCasePayloadConverter() },
});

Workers

Workers host workflows, activities, and Nexus services. Here's how to run a worker:

…

Notes about the above code:

  • This shows how to run a worker from C# using top-level statements. Of course this can be part of a larger program and ExecuteAsync can be used like an

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

C#c-sharpdotnetdurable-executionmicroservices

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言