我正在尝试将 Azure.Search 替换为 Azure.Search.Document。
我在 GetIndexesAsync 方法中发现了一个问题,该方法需要取消令牌。
我只是想知道如何实现这一点,以便我们可以获得该令牌并进一步进行。
请帮忙。
我尝试实现取消令牌,但它对我不起作用。 需要帮助来理解其具体的实施方式。
我尝试使用 Azure.Search.Documents 包使用示例 C# 控制台代码来使用取消令牌检索 Azure 搜索索引。
代码:
using Azure;
using Azure.Search.Documents;
using Azure.Search.Documents.Indexes;
using Azure.Search.Documents.Indexes.Models;
using System;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
string searchServiceEndpoint = "<SearchService_Endpoint>";
string adminApiKey = "<API_admin_key>";
Uri serviceEndpoint = new Uri(searchServiceEndpoint);
AzureKeyCredential credential = new AzureKeyCredential(adminApiKey);
SearchIndexClient indexClient = new SearchIndexClient(serviceEndpoint, credential);
using (CancellationTokenSource cts = new CancellationTokenSource())
{
try
{
cts.CancelAfter(TimeSpan.FromSeconds(30));
await GetIndexesAsync(indexClient, cts.Token);
}
catch (TaskCanceledException)
{
Console.WriteLine("Operation was canceled.");
}
catch (RequestFailedException ex)
{
Console.WriteLine($"Error getting indexes: {ex.Message}");
}
}
}
static async Task GetIndexesAsync(SearchIndexClient indexClient, CancellationToken cancellationToken)
{
await foreach (Page<SearchIndex> page in indexClient.GetIndexesAsync(cancellationToken: cancellationToken).AsPages())
{
foreach (SearchIndex result in page.Values)
{
Console.WriteLine($"Index Name: {result.Name}");
}
}
Console.WriteLine("Indexes retrieved successfully!");
}
}
输出:
代码成功运行并检索索引如下。