在数据库中可以使用事务,来保证多个操作的原子性(要么一起执行成功,如果有一个不成功,那么都不成功)
但是在处理不是涉及数据库的操作的时候,我如何做到这点呢。
比如我要写入2个文件,这个文件要么都写入成功,要么多失败,要同步。如果第一写入成功,第2个失败了,那么回到原始没有写入的状态。请教高手,我如何做到这点?

解决方案 »

  1.   

    bool resu 
    全局 操作1 赋值 resu= true;
    操作2 判断 resu
      

  2.   

    SqlConnection myConnection = new SqlConnection("Data Source=localhost;Initial Catalog=Northwind;Integrated Security=SSPI;");
    myConnection.Open();
    // 启动一个事务
    SqlTransaction myTrans = myConnection.BeginTransaction();
    // 为事务创建一个命令
    SqlCommand myCommand = new SqlCommand();
    myCommand.Connection=myConnection;
    myCommand.Transaction = myTrans;
    try
    {
    // 这里执行对 2个txt的 插入myTrans.Commit();
    Console.WriteLine("Both records are written to txt.");
    }
    catch(Exception e)
    {
    myTrans.Rollback();
    Console.WriteLine(e.ToString());
    Console.WriteLine("Neither record was written to txt.");
    }
    finally
    {
    myConnection.Close();
    }
      

  3.   

    using(TransactionScope scope = new TransactionScope())
    {
    //方法1   
    //方法2:   
    scope.Complete();
    }  
     
      

  4.   

    不好意思 不行。SqlTransaction 只适用于 sqlserver中的事务 。你要对txt之类的搞 回滚,ms可能 没有写 这样的类...
      

  5.   

    TransactionScope 貌似可以,梦大 知道的果然多,学习了.
      

  6.   

    或许只是我的幻想,.net里不能实现
      

  7.   

    用这个TransactionScope 很复杂的
    还不try{}catch{}呢String file1OldContents = File.ReadAllText(fileName1);
    String file2OldContents = File.ReadAllText(fileName2);try
    {
       File.AppendText(fileName1,file1NewContents);
       File.AppendText(fileName2,file2NewContents);
    }
    catch
    {
       File.WriteAllText(fileName1,file1OldContents );
       File.WriteAllText(fileName2,file2OldContents );
    }
      

  8.   

    SqlConnection myConnection = new SqlConnection("Data Source=localhost;Initial Catalog=Northwind;Integrated Security=SSPI;");
    myConnection.Open();
    // 启动一个事务
    SqlTransaction myTrans = myConnection.BeginTransaction();
    // 为事务创建一个命令
    SqlCommand myCommand = new SqlCommand();
    myCommand.Connection=myConnection;
    myCommand.Transaction = myTrans;
    try
    {
    // 这里执行对 2个txt的 插入myTrans.Commit();
    Console.WriteLine("Both records are written to txt.");
    }
    catch(Exception e)
    {
    myTrans.Rollback();
    Console.WriteLine(e.ToString());
    Console.WriteLine("Neither record was written to txt.");
    }
    finally
    {
    myConnection.Close();
    }
      

  9.   

    跟.NET没关系... ...
    SQLServer/Oracle/mysql等数据库的事务处理跟出错回滚是 产品 的功能,是其卖点之一.
    说白了,就是别人提供产品,提供的功能,你不能把这个功能理所当然的觉得所有其他系统都应该有,比如WINDOWS自身的文件管理系统(其实也有很弱的一点点,比如CTRL+Z,从内存中复原动作)其他的如果你想实现 事务处理 出错回滚,就必须自己实现了.而且实现起来并不难吧?每次保存文件之前备份一份,如果全部成功就不还原,否则将备份还原... ...
      

  10.   

    try catch就好了!try
    {
      //写入文件1
      //写入文件2
    }
    catch(Exception ex)
    {
      failed=true;
    }
    finally
    {
      if(failed)
        //恢复文件
    }