O processamento assíncrono (x-oss-async-process) permite que um programa execute outras tarefas sem aguardar a conclusão da tarefa atual. Este tópico descreve como usar o C# SDK V2 para transformar documentos de forma assíncrona.
Observações
O código de exemplo deste tópico usa a região China (Hangzhou) (cn-hangzhou). Por padrão, o sistema utiliza o endpoint público. Para acessar o OSS a partir de outros serviços do Alibaba Cloud na mesma região, use um endpoint interno. Para obter mais informações sobre os mapeamentos entre regiões e endpoints do OSS, consulte Regions and endpoints.
Código de exemplo
O código a seguir mostra como usar o C# SDK V2 para transformar um documento no formato desejado.
using System.Text;
using OSS = AlibabaCloud.OSS.V2; // Create an alias for Alibaba Cloud OSS SDK to simplify subsequent use.
var region = "cn-hangzhou"; // Required. The region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou.
var endpoint = null as string; // Optional. The endpoint used to access OSS. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var bucket = "your bucket name"; // Required. The name of the bucket.
var key = "your object key"; // Required. The name of the object that you want to transform.
// Load the default configurations of the OSS SDK. The configurations automatically read credential information (such as AccessKey) from environment variables.
var cfg = OSS.Configuration.LoadDefault();
// Explicitly set the use of environment variables to obtain credentials for identity verification (Format: OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET).
cfg.CredentialsProvider = new OSS.Credentials.EnvironmentVariableCredentialsProvider();
// Set the region of the bucket in the configuration.
cfg.Region = region;
// If an endpoint is specified, it overwrites the default endpoint.
if(endpoint != null)
{
cfg.Endpoint = endpoint;
}
// Create an OSS client instance using the configuration information.
using var client = new OSS.Client(cfg);
// Specify the destination bucket to store the transformed file.
var targetBucket = bucket!;
// Specify the key of the transformed file. Add the "process-" prefix for differentiation.
var targetKey = $"process-{key}";
// Construct a document processing style string to define the document transformation parameters.
// This configuration specifies the rule for transforming a source Docx document into a PNG image.
// Format description: doc/convert,target_{target_format},source_{source_format}
var style = "doc/convert,target_png,source_docx";
// Base64-encode the name of the destination bucket.
var targetNameBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(targetBucket));
// Base64-encode the key of the destination object.
var targetKeyBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(targetKey));
// Construct the complete processing instruction:
// 1. Apply the document transformation style (doc/convert).
// 2. Use the sys/saveas operation to save the result.
// - b_{Base64-encoded_bucket_name} specifies the destination bucket.
// - o_{Base64-encoded_key} specifies the destination key.
// - /notify enables the asynchronous processing mode.
var process = $"{style}|sys/saveas,b_{targetNameBase64},o_{targetKeyBase64}/notify";
// Call the AsyncProcessObjectAsync method to perform the document transformation.
var result = await client.AsyncProcessObjectAsync(new OSS.Models.AsyncProcessObjectRequest()
{
Bucket = bucket,
Key = key,
Process = process
});
// Print the result information.
Console.WriteLine("AsyncProcessObject done"); // Indicates that the operation is complete.
Console.WriteLine($"StatusCode: {result.StatusCode}"); // HTTP status code
Console.WriteLine($"RequestId: {result.RequestId}"); // The request ID, which is used for troubleshooting in Alibaba Cloud.
Console.WriteLine("Response Headers:"); // Response header information.
result.Headers.ToList().ForEach(x => Console.WriteLine(x.Key + " : " + x.Value)); // Traverse and print all response headers.
Console.WriteLine($"ProcessResult: {result.ProcessResult}"); // Output the processing result.
Referências
Para obter mais informações sobre a funcionalidade de processamento assíncrono, consulte Asynchronous Processing.
Para acessar o código de exemplo completo do processamento assíncrono, consulte AsyncProcessObject.cs.