gpt4 book ai didi

c# - 如何使用 IAsyncResult 从 WCF 异步中的回调中抛出异常

转载 作者:太空狗 更新时间:2023-10-29 19:45:17 27 4
gpt4 key购买 nike

我在我的项目中使用 WCF 异步调用,并且我使用的是客户端异步方法。我有一个像下面这样的场景 -

  //Code in Business Layer and this method is called from Web layer 
private void GetGeneralNews()
{
client.BeginGetGeneralNewsFeed(GeneralNewsCallback, null);
}

//Call Back Method
private static void GeneralNewsCallback(IAsyncResult asyncResult)
{
string response = string.Empty;

try
{
response = client.EndGetGeneralNewsFeed(asyncResult);
}
catch(Exception ex)
{
throw ex; // Here is the problem. It does not throw the exception to the web layer instead it will suppress the error.
}
}

因此,如上面的代码片段所示,它不会将异常从业务层抛出到 Web 层,因为它会在业务层本身中被抑制。

我查看了一些他们建议采用异步和等待方法的博客和网站,因为我有 .NET 4.0 框架并且我看到“生成基于任务的操作”选项被禁用.因此,如果有任何使用“IAsyncResult”(在客户端开始和结束)的选项,请告诉我。如果还有其他方法也欢迎。

请有人帮助我。

谢谢。

最佳答案

这是一个示例应用程序,它显示 WCF 不会吞噬异常。如果您没有收到异常,则它必须被您的服务器端代码吞没。

using System;
using System.ServiceModel;
using System.ServiceModel.Description;
using WcfQ.QServiceReference;

namespace WcfQ
{
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class QService : IQService
{
public void Foo()
{
throw new ApplicationException("Please catch this");
}
}

[ServiceContract]
public interface IQService
{
[OperationContract]
void Foo();
}

class Program
{
static private QServiceClient client;

static void Main(string[] args)
{
ServiceHost host = new ServiceHost(typeof(QService), new Uri("http://localhost:20001/q"));
AddWsdlSupport(host);
host.AddServiceEndpoint(typeof (IQService), new WSHttpBinding(SecurityMode.None), "");
host.Open();

client = new QServiceClient();
client.BeginFoo(FooCallback, null);
Console.WriteLine("ready");
Console.ReadKey();
}

private static void FooCallback(IAsyncResult asyncResult)
{
try
{
client.EndFoo(asyncResult);
}
catch (Exception ex)
{
Console.WriteLine("Got the exception: " + ex.Message);
}
}

static void AddWsdlSupport(ServiceHost svcHost)
{
ServiceMetadataBehavior smb = svcHost.Description.Behaviors.Find<ServiceMetadataBehavior>();
// If not, add one
if (smb == null)
smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
svcHost.Description.Behaviors.Add(smb);
// Add MEX endpoint
svcHost.AddServiceEndpoint(
ServiceMetadataBehavior.MexContractName,
MetadataExchangeBindings.CreateMexHttpBinding(),
"mex"
);

}
}

这是这个程序的输出:

ready 
Got the exception: Please catch this

关于c# - 如何使用 IAsyncResult 从 WCF 异步中的回调中抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29476660/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com