You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#控制台程序中异步并行执行代码及收尾处理需求

Hey there! Let's break down how to solve this exactly as you need it—running independent web service calls asynchronously in parallel, with shared cleanup and logging kicking off right after each task finishes. Here's a practical, production-ready approach for your C# console app:

Asynchronous Parallel Execution with Per-Task Cleanup/Logging

Core Strategy

We'll combine three key C# features to meet your requirements:

  • async/await for non-blocking web service calls (critical for I/O-bound work like API requests)
  • Task.WhenAll to run all independent tasks concurrently (maximizing performance without thread waste)
  • A shared cleanup/logging routine attached to each task, ensuring it runs immediately after the task completes (success or failure)

Step 1: Define the Shared Cleanup/Logging Method

First, create a thread-safe method to handle your shared logic. Since multiple tasks might call this in parallel, make sure any shared resources (like log files or databases) are accessed safely.

private static async Task CleanupAndLog(string taskIdentifier, Exception? failureException = null)
{
    // Replace with your actual cleanup logic (e.g., release HTTP clients, clear temp data)
    await Task.Delay(100); // Simulate async cleanup work

    // Logging logic (customize this to your needs)
    var timestamp = DateTime.Now.ToString("HH:mm:ss.fff");
    if (failureException == null)
    {
        Console.WriteLine($"[{timestamp}] ✅ Task {taskIdentifier} completed successfully");
    }
    else
    {
        Console.WriteLine($"[{timestamp}] ❌ Task {taskIdentifier} failed: {failureException.Message}");
        // Optional: Log full stack trace for debugging
        // Console.WriteLine(failureException.StackTrace);
    }
}

Step 2: Wrap Web Service Calls with Cleanup

Each web service task will wrap its API call in a try/catch/finally block, ensuring the shared cleanup runs regardless of success or failure.

private static async Task CallUserService()
{
    Exception? error = null;
    try
    {
        // Replace with your actual web service call (e.g., using HttpClient)
        Console.WriteLine("Starting User Service call...");
        await Task.Delay(2000); // Simulate API response time
    }
    catch (HttpRequestException ex)
    {
        error = ex;
        // Optional: Handle specific exceptions here before logging
    }
    finally
    {
        // Run shared cleanup/logging immediately after the task finishes
        await CleanupAndLog("UserService", error);
    }
}

private static async Task CallProductService()
{
    Exception? error = null;
    try
    {
        Console.WriteLine("Starting Product Service call...");
        await Task.Delay(1500); // Simulate API response time
    }
    catch (Exception ex)
    {
        error = ex;
    }
    finally
    {
        await CleanupAndLog("ProductService", error);
    }
}

// Add more web service tasks here as needed

Step 3: Run Tasks in Parallel

In your console app's entry point, start all tasks concurrently and wait for them to finish (including their cleanup steps).

For .NET 6+ (Top-Level Statements):

Console.WriteLine("=== Starting Parallel Web Service Calls ===");

// Start all tasks at once (concurrently)
var serviceTasks = new List<Task>
{
    CallUserService(),
    CallProductService()
    // Add additional tasks here
};

// Wait for all tasks (and their cleanup) to complete
await Task.WhenAll(serviceTasks);

Console.WriteLine("\n=== All Tasks & Cleanup Completed ===");

For Pre-.NET 6 (Traditional Main Method):

static async Task Main(string[] args)
{
    Console.WriteLine("=== Starting Parallel Web Service Calls ===");

    var serviceTasks = new List<Task>
    {
        CallUserService(),
        CallProductService()
    };

    await Task.WhenAll(serviceTasks);

    Console.WriteLine("\n=== All Tasks & Cleanup Completed ===");
}

Key Considerations

  • Thread Safety: If your cleanup/logging interacts with shared resources (like a log file), use locks or thread-safe libraries (e.g., Serilog, NLog) to avoid race conditions.
  • Error Isolation: Each task handles its own exceptions, so a failure in one web service call won't stop the others from running.
  • Efficiency: Since web service calls are I/O-bound, this approach doesn't waste threads waiting for responses—threads are freed up to handle other work while waiting.
  • Async All The Way: Ensure every method involved is async and you're properly awaiting tasks to avoid blocking the main thread.

内容的提问来源于stack exchange,提问作者Some User

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:44:34