gpt4 book ai didi

c# - 如果我的 C# 因存储过程调用而超时,该过程是否会继续运行?

转载 作者:可可西里 更新时间:2023-11-01 09:14:09 27 4
gpt4 key购买 nike

我有一个一般性的问题。如果我有一个调用 SQL Server 存储过程的 C# 应用程序,并且 C# 应用程序超时,服务器上的过程调用是否会继续运行直至完成?

最佳答案

没有。下面是复制品。当超时发生时,正在运行的进程将被终止,立即停止。如果您没有指定事务,则在超时之前已在存储过程中完成的工作将被保留。同样,如果与服务器的连接被某种外部力量切断,SQL Server 将终止正在运行的进程。

using (var conn = new SqlConnection(@"Data Source=.;Initial Catalog=Test;Integrated Security=True"))
{
conn.Open();

using (var setupTable = new SqlCommand(@"
IF NOT EXISTS (
SELECT *
FROM
sys.schemas s
INNER JOIN sys.tables t ON
t.[schema_id] = s.[schema_id]
WHERE
s.name = 'dbo' AND
T.name = 'TimeoutTest')
BEGIN
CREATE TABLE dbo.TimeoutTest
(
ID int IDENTITY(1,1) PRIMARY KEY,
CreateDate datetime DEFAULT(getdate())
);
END

-- remove any rows from previous runs
TRUNCATE TABLE dbo.TimeoutTest;", conn))
{
setupTable.ExecuteNonQuery();
}

using (var checkProcExists = new SqlCommand(@"
SELECT COUNT(*)
FROM
sys.schemas s
INNER JOIN sys.procedures p ON
p.[schema_id] = s.[schema_id]
WHERE
s.name = 'dbo' AND
p.name = 'AddTimeoutTestRows';", conn))
{
bool procExists = ((int)checkProcExists.ExecuteScalar()) == 1;

if (!procExists)
{
using (var setupProc = new SqlCommand(@"
CREATE PROC dbo.AddTimeoutTestRows
AS
BEGIN

DECLARE @stop_time datetime;

SET @stop_time = DATEADD(minute, 1, getdate());

WHILE getdate() < @stop_time
BEGIN
INSERT INTO dbo.TimeoutTest DEFAULT VALUES;

-- wait 10 seconds between inserts
WAITFOR DELAY '0:00:10';
END

END", conn))
{
setupProc.ExecuteNonQuery();
}
}
}

bool commandTimedOut = false;

try
{
using (var longExecution = new SqlCommand("EXEC dbo.AddTimeoutTestRows;", conn))
{
// The time in seconds to wait for the command to execute.
// Explicitly setting the timeout to 30 seconds for clarity.
longExecution.CommandTimeout = 30;

longExecution.ExecuteNonQuery();
}
}
catch (SqlException ex)
{
if (ex.Message.Contains("Timeout"))
{
commandTimedOut = true;
}
else
{
throw;
}
}

Console.WriteLine(commandTimedOut.ToString());

// Wait for an extra 30 seconds to let any execution on the server add more rows.
Thread.Sleep(30000);

using (var checkTableCount = new SqlCommand(@"
SELECT COUNT(*)
FROM
dbo.TimeoutTest t;", conn))
{
// Only expecting 3, but should be 6 if server continued on without us.
int rowCount = (int)checkTableCount.ExecuteScalar();

Console.WriteLine(rowCount.ToString("#,##0"));
}
}

Console.ReadLine();

产生以下输出

True
3

即使从 Management Studio 运行存储过程也会在一分钟内添加 6 行。

关于c# - 如果我的 C# 因存储过程调用而超时,该过程是否会继续运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36772989/

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