Skip to main content

Temporal Client - .NET SDK

A Temporal Client enables you to communicate with the Temporal Service. Communication with a Temporal Service lets you perform actions such as starting Workflow Executions, sending Signals and Queries to Workflow Executions, getting Workflow results, and more.

This page shows you how to do the following using the .NET SDK with the Temporal Client:

A Temporal Client cannot be initialized and used inside a Workflow. However, it is acceptable and common to use a Temporal Client inside an Activity to communicate with a Temporal Service.

Connect to development Temporal Service

Use TemporalClient.ConnectAsync to create a client. Connection options include the Temporal Server address, Namespace, and (optionally) TLS configuration. You can provide these options directly in code, or load them from environment variables and/or a TOML configuration file using the Temporalio.Client.EnvConfig helpers. We recommend environment variables or a configuration file for secure, repeatable configuration.

When you’re running a Temporal Service locally (such as with the Temporal CLI dev server), the required options are minimal. If you don't specify a host/port, most connections default to 127.0.0.1:7233 and the default Namespace.

You can use a TOML configuration file to set connection options for the Temporal Client. The configuration file lets you configure multiple profiles, each with its own set of connection options. You can then specify which profile to use when creating the Temporal Client. You can use the environment variable TEMPORAL_CONFIG_FILE to specify the location of the TOML file or provide the path to the file directly in code. If you don't provide the configuration file path, the SDK looks for it at the path ~/.config/temporalio/temporal.toml or the equivalent on your OS. Refer to Environment Configuration for more details about configuration files and profiles.

info

The connection options set in configuration files have lower precedence than environment variables. This means that if you set the same option in both the configuration file and as an environment variable, the environment variable value overrides the option set in the configuration file.

For example, the following TOML configuration file defines two profiles: default and prod. Each profile has its own set of connection options.

config.toml
# Default profile for local development
[profile.default]
address = "localhost:7233"
namespace = "default"

# Optional: Add custom gRPC headers
[profile.default.grpc_meta]
my-custom-header = "development-value"
trace-id = "dev-trace-123"

# Production profile for Temporal Cloud
[profile.prod]
address = "your-namespace.a1b2c.tmprl.cloud:7233"
namespace = "your-namespace"
api_key = "your-api-key-here"

# TLS configuration for production
[profile.prod.tls]
# TLS auto-enables when TLS config or an API key is present
# disabled = false
client_cert_path = "/etc/temporal/certs/client.pem"
client_key_path = "/etc/temporal/certs/client.key"

# Custom headers for production
[profile.prod.grpc_meta]
environment = "production"
service-version = "v1.2.3"

You can create a Temporal Client using a profile from the configuration file as follows. In this example, you load the default profile for local development:

LoadFromFile.cs
using Temporalio.Client;
using Temporalio.Client.EnvConfig;

namespace TemporalioSamples.EnvConfig;

/// <summary>
/// Sample demonstrating loading the default environment configuration profile
/// from a TOML file.
/// </summary>
public static class LoadFromFile
{
public static async Task RunAsync()
{
Console.WriteLine("--- Loading default profile from config.toml ---");

try
{
// For this sample to be self-contained, we explicitly provide the path to
// the config.toml file included in this directory.
// By default though, the config.toml file will be loaded from
// ~/.config/temporalio/temporal.toml (or the equivalent standard config directory on your OS).
var configFile = Path.Combine(Directory.GetCurrentDirectory(), "config.toml");

// LoadClientConnectOptions is a helper that loads a profile and prepares
// the config for TemporalClient.ConnectAsync. By default, it loads the
// "default" profile.
var connectOptions = ClientEnvConfig.LoadClientConnectOptions(new ClientEnvConfig.ProfileLoadOptions
{
ConfigSource = DataSource.FromPath(configFile),
});

Console.WriteLine($"Loaded 'default' profile from {configFile}.");
Console.WriteLine($" Address: {connectOptions.TargetHost}");
Console.WriteLine($" Namespace: {connectOptions.Namespace}");
if (connectOptions.RpcMetadata?.Count > 0)
{
Console.WriteLine($" gRPC Metadata: {string.Join(", ", connectOptions.RpcMetadata.Select(kv => $"{kv.Key}={kv.Value}"))}");
}

Console.WriteLine("\nAttempting to connect to client...");

var client = await TemporalClient.ConnectAsync(connectOptions);
Console.WriteLine("✅ Client connected successfully!");

// Test the connection by checking the service
var sysInfo = await client.Connection.WorkflowService.GetSystemInfoAsync(new());
Console.WriteLine("✅ Successfully verified connection to Temporal server!\n{0}", sysInfo);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
Console.WriteLine($"❌ Failed to connect: {ex.Message}");
}
}
}

Connect to Temporal Cloud

You can connect to Temporal Cloud using either an API key or through mTLS. Connection to Temporal Cloud or any secured Temporal Service requires additional connection options compared to connecting to an unsecured local development instance:

  • Your credentials for authentication.
    • If you are using an API key, provide the API key value.
    • If you are using mTLS, provide the mTLS CA certificate and mTLS private key.
  • Your Namespace and Account ID combination, which follows the format <namespace_id>.<account_id>.
  • The endpoint may vary. The most common endpoint used is the gRPC regional endpoint, which follows the format: <region>.<cloud_provider>.api.temporal.io:7233.
  • For Namespaces with High Availability features with API key authentication enabled, use the gRPC Namespace endpoint: <namespace>.<account>.tmprl.cloud:7233. This allows automated failover without needing to switch endpoints.

You can find the Namespace and Account ID, as well as the endpoint, on the Namespaces tab:

The Namespace and Account ID combination on the left, and the regional endpoint on the right

You can provide these connection options using environment variables, a configuration file, or directly in code.

You can use a TOML configuration file to set connection options for the Temporal Client. The configuration file lets you configure multiple profiles, each with its own set of connection options. You can then specify which profile to use when creating the Temporal Client. For a list of all available configuration options you can set in the TOML file, refer to Environment Configuration.

You can use the environment variable TEMPORAL_CONFIG_FILE to specify the location of the TOML file or provide the path to the file directly in code. If you don't provide the path to the configuration file, the SDK looks for it at the default path ~/.config/temporalio/temporal.toml.

info

The connection options set in configuration files have lower precedence than environment variables. This means that if you set the same option in both the configuration file and as an environment variable, the environment variable value overrides the option set in the configuration file.

For example, the following TOML configuration file defines a cloud profile with the necessary connection options to connect to Temporal Cloud via an API key:

# Cloud profile for Temporal Cloud
[profile.cloud]
address = "your-namespace.a1b2c.tmprl.cloud:7233"
namespace = "your-namespace"
api_key = "your-api-key-here"

If you want to use mTLS authentication instead of an API key, replace the api_key field with your mTLS certificate and private key:

# Cloud profile for Temporal Cloud
[profile.cloud]
address = "your-namespace.a1b2c.tmprl.cloud:7233"
namespace = "your-namespace"
tls_client_cert_data = "your-tls-client-cert-data"
tls_client_key_path = "your-tls-client-key-path"

With the connections options defined in the configuration file, use the ClientEnvConfig.LoadClientConnectOptions method to create a Temporal Client using the staging profile as follows. After loading the profile, you can also programmatically override specific connection options before creating the client.

LoadProfile.cs
using Temporalio.Client;
using Temporalio.Client.EnvConfig;

namespace TemporalioSamples.EnvConfig;

/// <summary>
/// Sample demonstrating loading a named environment configuration profile and
/// programmatically overriding its values.
/// </summary>
public static class LoadProfile
{
public static async Task RunAsync()
{
Console.WriteLine("--- Loading 'staging' profile with programmatic overrides ---");

try
{
var configFile = Path.Combine(Directory.GetCurrentDirectory(), "config.toml");
var profileName = "staging";

Console.WriteLine("The 'staging' profile in config.toml has an incorrect address (localhost:9999).");
Console.WriteLine("We'll programmatically override it to the correct address.");

// Load the 'staging' profile
var connectOptions = ClientEnvConfig.LoadClientConnectOptions(new ClientEnvConfig.ProfileLoadOptions
{
Profile = profileName,
ConfigSource = DataSource.FromPath(configFile),
});

// Override the target host to the correct address.
// This is the recommended way to override configuration values.
connectOptions.TargetHost = "localhost:7233";

Console.WriteLine($"\nLoaded '{profileName}' profile from {configFile} with overrides.");
Console.WriteLine($" Address: {connectOptions.TargetHost} (overridden from localhost:9999)");
Console.WriteLine($" Namespace: {connectOptions.Namespace}");

Console.WriteLine("\nAttempting to connect to client...");

var client = await TemporalClient.ConnectAsync(connectOptions);
Console.WriteLine("✅ Client connected successfully!");

// Test the connection by checking the service
var sysInfo = await client.Connection.WorkflowService.GetSystemInfoAsync(new());
Console.WriteLine("✅ Successfully verified connection to Temporal server!\n{0}", sysInfo);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
Console.WriteLine($"❌ Failed to connect: {ex.Message}");
}
}
}

Start a Workflow

How to start a Workflow using the Temporal .NET SDK

Workflow Execution semantics rely on several parameters—that is, to start a Workflow Execution you must supply a Task Queue that will be used for the Tasks (one that a Worker is polling), the Workflow Type, language-specific contextual data, and Workflow Function parameters.

A request to spawn a Workflow Execution causes the Temporal Service to create the first Event (WorkflowExecutionStarted) in the Workflow Execution Event History. The Temporal Service then creates the first Workflow Task, resulting in the first WorkflowTaskScheduled Event.

To start a Workflow Execution in .NET, use either the StartWorkflowAsync() or ExecuteWorkflowAsync() methods in the Client. You must set a Workflow Id and Task Queue in the WorkflowOptions given to the method.

var result = await client.ExecuteWorkflowAsync(
(MyWorkflow wf) => wf.RunAsync(),
new(id: "my-workflow-id", taskQueue: "my-task-queue");
Console.WriteLine("Result: {0}", result);

Get Workflow results

How to get the results of a Workflow Execution using the Temporal .NET SDK

If the call to start a Workflow Execution is successful, you will gain access to the Workflow Execution's Run Id.

The Workflow Id, Run Id, and Namespace may be used to uniquely identify a Workflow Execution in the system and get its result.

It's possible to both block progress on the result (synchronous execution) or get the result at some other point in time (asynchronous execution).

In the Temporal Platform, it's also acceptable to use Queries as the preferred method for accessing the state and results of Workflow Executions.

Use StartWorkflowAsync() or GetWorkflowHandle() to return a Workflow handle. Then use the GetResultAsync() method to await on the result of the Workflow.

To get a handle for an existing Workflow by its Id, you can use GetWorkflowHandle().

Then use DescribeAsync() to get the current status of the Workflow. If the Workflow does not exist, this call fails.

var handle = client.GetWorkflowHandle("my-workflow-id");
var result = await handle.GetResultAsync<string>();
Console.WriteLine("Result: {0}", result);