C# SqlDataAdapter填充未超时
我正在使用Sql Server对数据集运行填充操作,并且正在运行一个长时间存储的过程,该过程需要几分钟的时间才能运行。我希望得到一个“超时过期”异常,因为我将CommandTimeout设置为60秒C# SqlDataAdapter填充未超时,c#,ado.net,C#,Ado.net,我正在使用Sql Server对数据集运行填充操作,并且正在运行一个长时间存储的过程,该过程需要几分钟的时间才能运行。我希望得到一个“超时过期”异常,因为我将CommandTimeout设置为60秒 IDbCommand command = defaultConnection.CreateCommand(); command.CommandType = CommandType.StoredProcedure; command.CommandText = "Whatever"; command.C
IDbCommand command = defaultConnection.CreateCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "Whatever";
command.CommandTimeout = 60;
SqlCommand sqlCommand = (SqlCommand)command;
Logging.Log(SeverityTypeEnum.Diagnostic, "CommandTimeout = {0}", sqlCommand.CommandTimeout);
using (SqlDataAdapter adapter = new SqlDataAdapter(sqlCommand))
{
Logging.Log(SeverityTypeEnum.Diagnostic, "CommandTimeout = {0} {1} ", adapter.SelectCommand.CommandTimeout, adapter.SelectCommand.Connection.ConnectionTimeout);
adapter.Fill(dataSet, "MyDataSet");
}
上面的代码只是继续运行,没有异常发生。我已经打印了CommandTimeout,两个地方都是60。我还打印了ConnectionTimeout,即5,尽管我认为这与此无关。代码中提到的defaultConnection只是SqlConnection的包装
我对SqlDataReader使用了一个类似的过程。为什么我的填充没有超时?问题是填充是两阶段操作。第一个是执行查询,第二个是获取数据。CommandTimeout仅在第一个执行部分工作 答案是不使用CommandTimeout,而是使用BackgroundWorker异步运行查询。然后,您可以实现自己的超时,从而中止线程
private static readonly BackgroundWorker Worker = new BackgroundWorker { WorkerReportsProgress = true, WorkerSupportsCancellation = true };
private static readonly AutoResetEvent ResetEvent = new AutoResetEvent(false);
private static bool success;
private static void Main()
{
Worker.DoWork += worker_DoWork;
Worker.RunWorkerCompleted += WorkerRunWorkerCompleted;
var timer = new System.Timers.Timer(60000);
timer.Elapsed += TimerElapsed;
timer.Enabled = true;
Worker.RunWorkerAsync();
ResetEvent.WaitOne();
Logging.Log(SeverityTypeEnum.Information, (success)? "Mission succsessful" : "We have a problem Houston");
}
static void WorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Logging.Log(SeverityTypeEnum.Information, "Thankyou and goodnight");
success = true;
}
static void TimerElapsed(object sender, ElapsedEventArgs e)
{
Logging.Log(SeverityTypeEnum.Information, "Time please Gentlemen, time!");
ResetEvent.Set(); // aborts worker
}
private static void WorkerDoWork(object sender, DoWorkEventArgs e)
{
// create SqlCommand, SqlDataAdapter and call Fill as before
}
您是否尝试过使用较低的超时值?只是为了测试?试着不设置它,那么它应该默认为30秒。如果我将超时设置为非常低的值,比如1秒或2秒,它确实有效。这就好像一旦查询开始返回数据,填充就不会超时。