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:
Extensions:
System.Diagnostics.Metrics support for SDK metricsContents
Add the Temporalio package from NuGet. For example, using the dotnet
CLI:
dotnet add package TemporalioThe .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.
Assuming the ImplicitUsings is
enabled, create an activity by putting the following in MyActivities.cs:
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.
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.
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:
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!A client can be created and used to start a workflow. For example:
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:
Tls option can be set to a non-null TlsOptions instance.StartWorkflowAsync + GetResultAsync above, there is an ExecuteWorkflowAsync extension method that is
clearer if the handle is not needed.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.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.handle above represents a WorkflowHandle which has specific workflow operations on it. For existing workflows,
handles can be obtained via client.GetWorkflowHandle.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:
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 connection options can be loaded from a temporal.toml file and environment variables:
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.
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 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:
nullbyte[]Google.Protobuf.IMessage instancesSystem.Text.Json supportsIRawValue as unconverted raw payloadsCustom 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:
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 host workflows, activities, and Nexus services. Here's how to run a worker:
…Notes about the above code:
ExecuteAsync can be used like an暂无开放 Issues,或尚未同步最近议题。