如何用SvcUtil.exe生成可异步调用的WCF客户端?
Absolutely! You don’t have to struggle with missing async client methods—SvcUtil.exe has built-in support to generate both traditional event-based async methods and modern task-based async methods (for .NET 4.5+) for your WCF service. Here’s exactly how to do it, tailored to your service contract:
Step 1: Generate Async Client Code with SvcUtil.exe
Depending on which async pattern you prefer, use one of these command-line arguments:
Option 1: Task-Based Async (Recommended for .NET 4.5+)
This generates clean, Task<bool>-returning methods that work with await—the modern, most readable approach:
SvcUtil.exe http://your-service-endpoint/Service1.svc /async:TaskBased /out:ServiceClient.cs /config:App.config
Replace http://your-service-endpoint/Service1.svc with your actual service URL.
Option 2: Event-Based Async (Legacy Pattern)
If you need compatibility with older .NET versions, use the /async flag to generate Begin/End method pairs and completed events:
SvcUtil.exe http://your-service-endpoint/Service1.svc /async /out:ServiceClient.cs /config:App.config
Step 2: Use the Generated Async Methods
Once you’ve generated the client code, add it to your project and reference the necessary WCF assemblies. Here’s how to call the async methods:
Task-Based Example (Modern)
using (var client = new Service1Client()) { try { bool result = await client.BooleanMethodAsync(); // Do something with the boolean result here Console.WriteLine($"Service returned: {result}"); } catch (FaultException ex) { // Handle service-specific faults Console.WriteLine($"Service fault: {ex.Message}"); } catch (Exception ex) { // Handle general errors Console.WriteLine($"Error: {ex.Message}"); } }
Event-Based Example (Legacy)
using (var client = new Service1Client()) { // Hook up the completed event handler client.BooleanMethodCompleted += (sender, e) => { if (e.Error == null) { bool result = e.Result; Console.WriteLine($"Service returned: {result}"); } else { Console.WriteLine($"Error: {e.Error.Message}"); } }; // Start the async call client.BeginBooleanMethod(null, null); }
Key Notes
- Your existing service contract doesn’t need any changes—WCF allows clients to call synchronous service methods asynchronously without modifying the server-side code.
- Make sure your client project targets a .NET version that supports your chosen async pattern (e.g., .NET 4.5+ for task-based async).
内容的提问来源于stack exchange,提问作者Bernal Bogantes Conejo

