简体   繁体   English

线程中的异常处理,联系WCF服务

[英]Exception handling in threads, contacting a WCF service

I have question in regards to exception handling in threads. 我对线程中的异常处理有疑问。 I have a simple WCF service which takes some bytes as input. 我有一个简单的WCF服务,它需要一些字节作为输入。 This WCF Service is called from a console application. 从控制台应用程序调用此WCF服务。

Method Snippet(MyMethod) 方法片段(MyMethod)

try 
{
   _service.ImportBytes(bytes);
   _service.Close();

}
catch(Exception e) 
{
   _logger.Error(e.Message);
   _service.Abort();
}

If this is method called directly from the Main thread the exception will occur, since my service is taken down(Stopped the application in IIS). 如果这是直接从主线程调用的方法,则会发生异常,因为我的服务已关闭(IIS中的应用程序已停止)。

But if It's calledfrom a thread, the exception will never occur: 但是,如果从线程调用它,则永远不会发生异常:

 var thread = new Thread(() => MyMethod(file);
 thread.Start()

Since this method should be called several times, in a foreach loop I figured out that if I create one thread for each of the files. 由于应该多次调用此方法,因此在foreach loop我发现如果为每个文件创建一个线程。 If one thread fails, it should just logg it and die, so it doesn't interrupt the application itself. 如果一个线程失败,则应该记录该线程并使其死亡,因此它不会中断应用程序本身。

How should I handle exceptions inside a thread? 我应该如何处理线程内的异常?

In .NET 4.0 the Task Parallel Library (TPL) is added. 在.NET 4.0中,添加了任务并行库(TPL)。 This is the preferred way to work with threading. 这是使用线程的首选方式。

A Task is an object that encapsulates an operation that will return a value at some point or an exception. Task是封装操作的对象,该操作将在某个时刻或发生异常时返回值。

The basic idea is that you do something like this: 基本思想是您可以执行以下操作:

Task.Run(() => { /* your code */ });

This will return a Task object that finishes when the inner code is finished. 这将返回在内部代码完成时完成的Task对象。 You can schedule continuations on such a Task object to run whenever that happens. 您可以安排在此类Task对象上继续执行以在发生任何情况时运行。 But since you are executing WCF service calls you can make your life easier by letting Visual Studio generate asynchronous methods for you. 但是,由于您正在执行WCF服务调用,因此可以通过让Visual Studio为您生成异步方法来使您的生活更轻松。 Especially since WCF methods are a form of asynchronous I/O and you can consume these without having to wrap them in a thread yourself. 特别是由于WCF方法是异步I / O的一种形式,因此您可以使用它们而不必自己将它们包装在线程中。

This means that all your methods end with the postfix 'Async' and return a Task object. 这意味着您的所有方法都以后缀“ Async”结尾并返回Task对象。 By using async and await you can easily consume these. 通过使用异步和等待,您可以轻松使用它们。 By using Task.WhenAll you can let multiple Tasks run in parallel. 通过使用Task.WhenAll您可以让多个Task.WhenAll并行运行。 Task.WhenAll will return a Task in the Faulted state with all the exceptions that where thrown by one of your Tasks when something goes wrong. Task.WhenAll会返回一个TaskFaulted状态与在那里你的任务之一,当出现错误抛出的所有异常。

Here is some documentation on using async and wait with WCF services that should get you started. 这是一些有关使用异步并等待WCF服务的文档 ,它们可以帮助您入门。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM