WCF中的File.Move()操作无法处理事务

本文关键字:处理 事务 操作 中的 File Move WCF | 更新日期: 2023-09-27 18:17:16

场景:我在本地系统中有三个文件夹。我想将文件从"源1"移动到"源2"(这是WCF服务1中的一个任务),然后从"源2"移动到"目的地"(这是WCF服务2中的另一个任务)。如果任何事务失败,那么文件应该在"源1"中。

但是发生的是,服务2成功地将文件从"源1"移动到"源2"。服务1试图将相同的文件从"源2"移动到"目的地",但失败了。所以我的文件应该在"源1"中。但我发现它在"来源2"。

请帮我一下。并告诉我在WCF中是否可能。

客户端代码

ITransactionSupportService wsChannel = new ChannelFactory<ITransactionSupportService>("wsEndPoint").CreateChannel();
var result = wsChannel.FileMoveService1();

Service1 Code: Method FileMoveService1()

ITransactionSupport2Service svcMultipleSvcChanel = new ChannelFactory<ITransactionSupport2Service>("netPipeConfig").CreateChannel();
bool flag = svcMultipleSvcChanel.FileMoveService2();
if (File.Exists(@"D:'Transaction File Movement'Source 2'Trans.txt"))
{
   **throw new Exception("Test");**
   File.Copy(@"D:'Transaction File Movement'Source 2'Trans.txt", @"D:'Transaction File Movement'Destination'Trans.txt");
}

Service2 Code: Method FileMoveService2()

if (File.Exists(@"D:'Transaction File Movement'Source 1'Trans.txt"))
   File.Move(@"D:'Transaction File Movement'Source 1'Trans.txt", @"D:'Transaction File Movement'Source 2'Trans.txt");
   return true;

提前感谢Nitish

WCF中的File.Move()操作无法处理事务

文件操作不支持事务。您需要手动处理回滚。

您可以通过在TransactionScope中登记您的文件操作来实现。它是这样做的(未测试代码,您必须完成它):

public class FileMover : IEnlistmentNotification
{
    private readonly string _source;
    private readonly string _destination;
    public FileMover(string source, string destination)
    {
        Transaction.Current.EnlistVolatile(this, EnlistmentOptions.None);
        _source = source;
        _destination = destination;
        File.Move(_source, _destination);
    }
    public void Commit(Enlistment enlistment)
    {
        enlistment.Done();
    }
    public void InDoubt(Enlistment enlistment)
    {
        enlistment.Done();
    }
    public void Prepare(PreparingEnlistment preparingEnlistment)
    {
        preparingEnlistment.Prepared();
    }
    public void Rollback(Enlistment enlistment)
    {
        File.Move(_destination, _source);
        enlistment.Done();
    }
} 

http://msdn.microsoft.com/en-us/library/system.transactions.ienlistmentnotification (v = vs.110) . aspx