使用中的多个TransactionScope.Complete()

时间:2016-10-12 23:57:46

标签: c# .net transactionscope

我有这样的代码

USE msdb;
GO

--add a job
EXEC dbo.sp_add_job
    @job_name = N'FullBackup';
GO

USE msdb;
GO

--add jobsteps to jobsteps
DECLARE @fileName VARCHAR(90);
DECLARE @db_name VARCHAR(20);
DECLARE @fileDate VARCHAR(20);
DECLARE @commandtxt VARCHAR(100);

SET @fileName = 'D:\SQL server\BackUp\'; 
--SET @db_name = 'AdventureWorks_';    
SET @fileDate = CONVERT(VARCHAR(8), GETDATE(),112);
SET @fileName = @fileName + @db_name + RTRIM(@fileDate) + '.bak';

SET @commandtxt = N'''BACKUP DATABASE [AdventureWorks2012] TO DISK =N''' + @fileName + ''' WITH INIT';

EXEC sp_add_jobstep
    @job_name = N'FullBackup',
    @step_name = N'Weekly Full Backup',
    @subsystem = N'TSQL',
    @command = 'BACKUP DATABASE [AdventureWorks2012] TO DISK =N''' + @fileName + ''' WITH INIT',
    @retry_attempts = 5,
    @retry_interval = 5;
GO

--Create a Schedule for this job, backup, occurs once a week each friday at 11:59
EXEC sp_add_schedule
    @schedule_name = N'WeeklyBackup1',
    @freq_type = 8,
    @freq_interval = 32,
    @freq_recurrence_factor = 1,
    @active_start_time = 235900;
GO

--attach the schedule to the job
EXEC sp_attach_schedule
    @job_name = N'FullBackup',
    @schedule_name = N'WeeklyBackup1';
GO

EXEC dbo.sp_add_jobserver
    @job_name = N'FullBackup';
GO

我想像这样添加try { MyModel model = repo.GetData(); if(model == null) { return model; } else { MyResponse response = checkData(); if(response) { return model; } UpdateData(); } } catch(Exception e) { .... } return model;

TransactionScope

我想问一下,如果我在代码到达try { using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted })) { MyModel model = repo.GetData(); if(model == null) { return model; } else { MyResponse response = checkData(); if(response) { return model; } UpdateData(); } ts.Complete(); } } catch(Exception e) { .... } return model 之前有多个return声明,那可以吗?我无法在ts.Complete()块中将ts设置为null,因为finally位于try块内。

1 个答案:

答案 0 :(得分:1)

回答你的问题:在trans.Complete()之前返回是否可以? - 是的。交易不会被提交,也不会进行更改。这就是它的工作原理。

即使发生异常(或返回),using语句也会在任何参数中运行.Dispose()。

当处理事务时,如果调用了trans.Complete(),它将被提交,如果没有调用则不会应用任何更改。

关于使用声明: What is the C# Using block and why should I use it?

关于Transaction.Dispose(): https://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.dispose(v=vs.110).aspx