简体   繁体   English

c#MySql存储过程超时

[英]c# MySql stored procedure timeout

I have ac# application that calls the same mysql stored procedure multiple times with different parameters.我有 ac# 应用程序,它使用不同的参数多次调用相同的 mysql 存储过程。 Its called about 250 times and each call takes about 30 seconds to complete.它被调用了大约 250 次,每次调用大约需要 30 秒才能完成。 There are some cases when for some reason a call takes much more time, and it blocks the next ones from running, so I would like to set a timeout for the stored procedures to stop when it takes more than say like 5 minutes.在某些情况下,由于某种原因调用需要更多时间,并且它会阻止下一个调用运行,因此我想为存储过程设置超时以在需要超过 5 分钟时停止。 This way the others could still run and only the one that took too much time would be skipped.这样其他人仍然可以运行,只有花费太多时间的人会被跳过。 I tried to use the command timeout of the mysql connection, but this does not kill the running stored procedure, only throws an exception in code which is not ideail because the next call will start while the previous one is still running.我尝试使用 mysql 连接的命令超时,但这不会终止正在运行的存储过程,只会在代码中抛出一个不理想的异常,因为下一个调用将在前一个调用仍在运行时开始。

Is there a way to set a mysql timout for the connection, or just kill a mysql thread/process (the sp) if it takes too much time?有没有办法为连接设置 mysql 超时,或者如果需要太多时间就杀死一个 mysql 线程/进程(sp)? Closing the mysql command or connection did not do it, and clearing the connection pool did not help either.关闭 mysql 命令或连接也没有用,清除连接池也没有用。

To kill a running stored procedure, use MySqlCommand.Cancel (using the same MySqlCommand object that was used to start that stored procedure).MySqlCommand.Cancel正在运行的存储过程,请使用MySqlCommand.Cancel (使用用于启动该存储过程的相同MySqlCommand对象)。 Because MySqlCommand.ExecuteNonQuery (or ExecuteReader , etc.) will block the thread that called it, this will have to be done from another thread.因为MySqlCommand.ExecuteNonQuery (或ExecuteReader等)会阻塞调用它的线程,所以这必须从另一个线程完成。 One way to accomplish this would be with CancellationTokenSource , then registering a callback that will cancel the command:完成此操作的一种方法是使用CancellationTokenSource ,然后注册将取消命令的回调:

// set up command
using (var command = new MySqlCommand("sproc_name", connection))
{
    command.CommandType = CommandType.StoredProcedure;

    // register cancellation to occur in five minutes
    using (var cts = new CancellationTokenSource(TimeSpan.FromMinutes(5)))
    using (cts.Token.Register(() => command.Cancel())
    {
        // execute the stored procedure as normal
        using (var reader = command.ExecuteReader())
        {
            // use reader, or just call command.ExecuteNonQuery instead if that's what you need
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM