I
I
isxaker2014-09-10 15:37:00
SQL
isxaker, 2014-09-10 15:37:00

Is it always necessary to call EndExecuteReader?

When a form is opened ( .net4, WinForm app, one SqlConnection for the whole application ) in the Load event handler , a long request to the database occurs, which is executed asynchronously. If the user gets tired of waiting, he clicks on the cross, the form closes. How to clear SqlDaraReader in this case ?

public static SqlDataReader SafeExecuteReader(SqlCommand command, AutoResetEvent evtCancel)
{
       IAsyncResult res = command.BeginExecuteReader();
       Int32 index = WaitHandle.WaitAny(new WaitHandle[] { res.AsyncWaitHandle, evtCancel }, command.CommandTimeout * 1000);
       if (index == 1 && !res.IsCompleted)
            {
                try
                {
                    //например так?
                    //SqlDataReader reader = command.EndExecuteReader(res);
                    //if (reader != null) reader.Close();
                }
                catch (SqlException /*sex*/) { }
                return null;
            }
            else if (!res.IsCompleted)
            {
                //command.EndExecuteReader(res);
                throw new Exception("Timeout");
            }
            return command.EndExecuteReader(res);
}

Or is the EndExecuteReader only needed to complete the asynchronous execution and return the requested SqlDataReader ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
aush, 2014-09-10
@aush

I advise you to study the patterns of asynchronous programming, now you have a mess. You can start here msdn.microsoft.com/en-us/library/jj152938(v=vs.110...
BeginExecuteReader and EndExecuteReader implement the now deprecated Asynchronous Programming Model (APM).
SqlDataReader implements IDisposable, so if the operation succeeds completed, you should call Dispose() on it when you're done with it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question