{"meta":{"title":"複雑なアルゴリズムまたはロジックの説明","intro":"Copilot Chat は、複雑なアルゴリズムやロジックに関する明確で簡潔なドキュメントを追加するのに役立ちます。","product":"GitHub Copilot","breadcrumbs":[{"href":"/ja/copilot","title":"GitHub Copilot"},{"href":"/ja/copilot/tutorials","title":"チュートリアル"},{"href":"/ja/copilot/tutorials/copilot-cookbook","title":"GitHub Copilot クックブック"},{"href":"/ja/copilot/tutorials/copilot-cookbook/document-code","title":"コードを文書化する"},{"href":"/ja/copilot/tutorials/copilot-cookbook/document-code/explain-complex-logic","title":"複雑なロジックを説明する"}],"documentType":"article"},"body":"# 複雑なアルゴリズムまたはロジックの説明\n\nCopilot Chat は、複雑なアルゴリズムやロジックに関する明確で簡潔なドキュメントを追加するのに役立ちます。\n\nコードの複雑なアルゴリズムやロジックを説明することが必要になる場合があります。 これは、他のユーザーに理解させようとしているときは特に、困難な場合があります。\nCopilot Chat は、アルゴリズムまたはロジックを明確かつ簡潔な方法で説明する方法に関する提案を提供することで、このタスクに役立ちます。\n\n## サンプル シナリオ\n\n次の C# コードのメソッドは、データをフェッチし、エラーが発生した場合は再試行して、状態ラベルを更新します。 メソッドがどのように動作し、再試行とキャンセルを処理するかを、コード内のコメントで説明したい場合があります。\n\n```csharp id=fetch-data-with-retry\nprivate static readonly HttpClient _client = new HttpClient();\n\npublic async Task<string> FetchDataFromApiWithRetryAsync(string apiUrl, CancellationToken cancellationToken, int maxRetries, int cancellationDelay, Label statusLabel)\n{\n    var retryCount = 0;\n    using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);\n\n    while (retryCount < maxRetries)\n    {\n        try\n        {\n            cts.CancelAfter(cancellationDelay);\n            return await FetchDataFromApiAsync(cts.Token, statusLabel);\n        }\n        catch (Exception ex) when (!(ex is OperationCanceledException))\n        {\n            if (retryCount < maxRetries - 1) {\n                retryCount++;\n                int delay = (int)Math.Pow(2, retryCount) * 1000;\n                await Task.Delay(delay, cancellationToken);\n                UpdateStatusLabel($\"Retrying ({retryCount}/{maxRetries})...\", statusLabel);\n            } else {\n                throw new Exception($\"Failed to fetch data after {maxRetries} retries: {ex.Message}\", ex);\n            }\n        }\n    }\n\n    throw new OperationCanceledException(\"The operation was cancelled.\", cts.Token);\n}\n\nprivate async Task<string> FetchDataFromApiAsync(string apiUrl, CancellationToken cancellationToken, Label statusLabel)\n{\n    UpdateStatusLabel(\"Fetching data...\", statusLabel);\n\n    HttpResponseMessage response = await _client.GetAsync(apiUrl, cancellationToken);\n    response.EnsureSuccessStatusCode();\n    string data = await response.Content.ReadAsStringAsync();\n\n    UpdateStatusLabel(\"Data fetched.\", statusLabel);\n    return data;\n}\n\nprivate void UpdateStatusLabel(string message, Label statusLabel)\n{\n    if (statusLabel.InvokeRequired) {\n        statusLabel.BeginInvoke(new Action<string, Label>(UpdateStatusLabel), message, statusLabel);\n    } else {\n        statusLabel.Text = message;\n    }\n}\n```\n\n## プロンプトの例\n\nコメントを使用してこのコードを理解しやすくするために、 Copilot Chat に依頼できます。\n\n```copilot copy prompt ref=fetch-data-with-retry\nAdd comments to this code to make it more understandable\n```\n\n## 応答の例\n\n> \\[!NOTE] 次の応答は例です。 Copilot Chat の応答は非決定的であるため、ここで示したものとは異なる応答が返される可能性があります。\n\nCopilot は、提案された更新プログラムの概要と、コメントが追加されたコード スニペットで応答します。\n\n```csharp\n// Shared HttpClient instance for making HTTP requests (best practice for reuse)\nprivate static readonly HttpClient _client = new HttpClient();\n\n/// <summary>\n/// Fetches data from an API with retry mechanism and timeout functionality\n/// </summary>\n/// <param name=\"apiUrl\">The URL to fetch data from</param>\n/// <param name=\"cancellationToken\">Token to cancel the operation</param>\n/// <param name=\"maxRetries\">Maximum number of retry attempts</param>\n/// <param name=\"cancellationDelay\">Timeout duration in milliseconds</param>\n/// <param name=\"statusLabel\">UI label to show status updates</param>\npublic async Task<string> FetchDataFromApiWithRetryAsync(string apiUrl, CancellationToken cancellationToken, int maxRetries, int cancellationDelay, Label statusLabel)\n{\n    var retryCount = 0;\n    // Create a linked cancellation token that combines user cancellation and timeout\n    using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);\n\n    while (retryCount < maxRetries)\n    {\n        try\n        {\n            // Set timeout for this attempt\n            cts.CancelAfter(cancellationDelay);\n            return await FetchDataFromApiAsync(cts.Token, statusLabel);\n        }\n        catch (Exception ex) when (!(ex is OperationCanceledException))\n        {\n            // If not the last retry attempt, implement exponential backoff\n            if (retryCount < maxRetries - 1) {\n                retryCount++;\n                // Exponential backoff: 2^retryCount seconds (1s, 2s, 4s, 8s, etc.)\n                int delay = (int)Math.Pow(2, retryCount) * 1000;\n                await Task.Delay(delay, cancellationToken);\n                UpdateStatusLabel($\"Retrying ({retryCount}/{maxRetries})...\", statusLabel);\n            } else {\n                // If all retries failed, throw exception with details\n                throw new Exception($\"Failed to fetch data after {maxRetries} retries: {ex.Message}\", ex);\n            }\n        }\n    }\n\n    // This is reached if maxRetries is 0 or some other unexpected case\n    throw new OperationCanceledException(\"The operation was cancelled.\", cts.Token);\n}\n\n/// <summary>\n/// Makes the actual API call to fetch data\n/// </summary>\nprivate async Task<string> FetchDataFromApiAsync(string apiUrl, CancellationToken cancellationToken, Label statusLabel)\n{\n    UpdateStatusLabel(\"Fetching data...\", statusLabel);\n\n    // Perform HTTP GET request with cancellation support\n    HttpResponseMessage response = await _client.GetAsync(apiUrl, cancellationToken);\n    response.EnsureSuccessStatusCode(); // Throws if response is not successful\n    string data = await response.Content.ReadAsStringAsync();\n\n    UpdateStatusLabel(\"Data fetched.\", statusLabel);\n    return data;\n}\n\n/// <summary>\n/// Updates UI label text safely across threads\n/// </summary>\n/// <param name=\"message\">The message to display</param>\n/// <param name=\"statusLabel\">The label control to update</param>\nprivate void UpdateStatusLabel(string message, Label statusLabel)\n{\n    // Check if we need to invoke on UI thread\n    if (statusLabel.InvokeRequired) {\n        // Use BeginInvoke to update label on UI thread\n        statusLabel.BeginInvoke(new Action<string, Label>(UpdateStatusLabel), message, statusLabel);\n    } else {\n        // Direct update if already on UI thread\n        statusLabel.Text = message;\n    }\n}\n```\n\n## 詳細については、次を参照してください。\n\n* [GitHub Copilot Chat のプロンプト エンジニアリング](/ja/copilot/concepts/prompting/prompt-engineering)\n* [GitHub Copilot の使用に関するベスト プラクティス](/ja/copilot/get-started/best-practices)"}