Ejemplo n.º 1
0
 public static Task<SqlDataReader> ExecuteReaderAsync(this SqlCommand command)
 {
     return Task.Factory.FromAsync(
         (cb, state) => command.BeginExecuteReader(cb, state, CommandBehavior.CloseConnection),
         iar => command.EndExecuteReader(iar),
         null);
 }
        public static Task<SqlDataReader> ExecuteReaderAsync(this SqlCommand source, CommandBehavior behavior)
        {
            AsyncCallback callback = null;

            TaskCompletionSource<SqlDataReader> tcs = new TaskCompletionSource<SqlDataReader>(null, TaskCreationOptions.None);
            try
            {
                if (callback == null)
                {
                    callback = delegate(IAsyncResult iar)
                    {
                        Exception exception = null;
                        OperationCanceledException exception2 = null;
                        SqlDataReader result = default(SqlDataReader);
                        try
                        {
                            result = source.EndExecuteReader(iar);
                        }
                        catch (OperationCanceledException exception3)
                        {
                            exception2 = exception3;
                        }
                        catch (Exception exception4)
                        {
                            exception = exception4;
                        }
                        finally
                        {
                            if (exception2 != null)
                            {
                                tcs.TrySetCanceled();
                            }
                            else if (exception != null)
                            {
                                tcs.TrySetException(exception);
                            }
                            else
                            {
                                tcs.TrySetResult(result);
                            }
                        }
                    };
                }

                source.BeginExecuteReader(callback, null, behavior);
            }
            catch
            {
                tcs.TrySetResult(default(SqlDataReader));
                throw;
            }

            return tcs.Task;
        }
        /// <summary>
        /// Extends BeginExecuteReader so that when a state object is not needed, null does not need to be passed.
        /// <example>
        /// sqlcommand.BeginExecuteReader(callback, behavior);
        /// </example>
        /// </summary>
        public static IAsyncResult BeginExecuteReader(this SqlCommand sqlcommand, AsyncCallback callback, System.Data.CommandBehavior behavior)
        {
            if(sqlcommand == null) throw new ArgumentNullException("sqlcommand");

            return sqlcommand.BeginExecuteReader(callback, null, behavior);
        }