wcf 不会rollback,请大家帮忙看看。
在学习wcf,最近学到wcf事务。自己写了一个示例,就是不会rollback,请大家帮忙看看。
服务器端代码:
namespace Host
{
class Program
{
static void Main(string[] args)
{
ServiceHost host = new ServiceHost(typeof(Calc));
WSHttpBinding wsbinding = new WSHttpBinding();
wsbinding.TransactionFlow = true;
host.AddServiceEndpoint(typeof(ICalc), wsbinding, "http://localhost:8003");
host.Opened += delegate
{
Console.WriteLine("services is open!");
};
host.Open();
Console.ReadKey();
}
}
[ServiceContract]
public interface ICalc
{
[OperationContract]
[TransactionFlow(TransactionFlowOption.Mandatory)]
double Add(double x);
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class Calc : ICalc
{
[OperationBehavior(TransactionScopeRequired = true)]
public double Add(double x)
{
Console.WriteLine(Transaction.Current.TransactionInformation.CreationTime);
Console.WriteLine(Transaction.Current.TransactionInformation.LocalIdentifier);
return x + 1;
}
}
}
然后客户端代码:
class Program
{
static void Main(string[] args)
{
WSHttpBinding ws = new WSHttpBinding();
ws.TransactionFlow=true;
ChannelFactory<ICalc> mychannel = new ChannelFactory<ICalc>(ws, "http://localhost:8003");
mychannel.Open();
ICalc myclient = mychannel.CreateChannel();
double x = 3.5;
double y = 0;
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required))
{
try
{
Console.WriteLine(Transaction.Current.TransactionInformation.CreationTime);
Console.WriteLine(Transaction.Current.TransactionInformation.LocalIdentifier);
y = myclient.Add(x);
throw new Exception("throw new exception");
scope.Complete();
mychannel.Close();
}
catch (Exception ex)
{
Transaction.Current.Rollback();
mychannel.Abort();
Console.WriteLine(ex.Message);
}
}
Console.WriteLine(x);
Console.WriteLine(y);
Console.ReadKey();
}
}
然后每次都是打印
x=3.5
y=4.5
好郁闷啊,我不是有抛出异常了吗?为什么不会Rollback呢。
[解决办法]
把上面的代码 throw new Exception("throw new exception");
改为:int x=int.Parse("abc");
再试一下。
[解决办法]
另外有时间去看一下.net平台下错误处理机制。
特别是错误的传递过程。
[解决办法]
你这不是数据库操作,没用到事务呀
*****************************************************************************
签名档: http://feiyun0112.cnblogs.com/
[解决办法]
印象中TransactionScope这个要配置机器的,以前在弄sql事务时遇过,不过很遗憾,我也没配成功过,具体方法可搜索“TransactionScope配置”,不知是不是这个原因。
[解决办法]
将服务端的Distributed Transcation Coordinator服务启用