zhaolei
2020-11-20 921de2254ff5712a44ed8575ee8efe34252f6603
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using System;
using System.Data;
using System.Data.Common;
using System.Threading.Tasks;
 
namespace PetaPoco.Utilities
{
#if ASYNC
    public class AsyncReader<T> : IAsyncReader<T>
    {
        private readonly bool _isAsync;
        private readonly Func<IDataReader, T> _pocoFactory;
        private IDbCommand _cmd;
        private IDatabase _db;
        private IDataReader _reader;
        private DbDataReader Reader => (DbDataReader) _reader;
 
        private AsyncReader()
        {
        }
 
        public AsyncReader(IDatabase db, IDbCommand cmd, IDataReader reader, Func<IDataReader, T> pocoFactory)
        {
            _db = db;
            _cmd = cmd;
            _reader = reader;
            _pocoFactory = pocoFactory;
            _isAsync = reader is DbDataReader;
        }
 
        public T Poco { get; private set; }
 
        public async Task<Boolean> ReadAsync()
        {
            if (_reader == null)
                return false;
 
            Poco = default(T);
 
            var hasRecords = _isAsync ? await Reader.ReadAsync() : _reader.Read();
 
            if (hasRecords)
                Poco = _pocoFactory(_reader);
 
            return hasRecords;
        }
 
        public void Dispose()
        {
            _reader?.Dispose();
            _reader = null;
 
            _cmd?.Dispose();
            _cmd = null;
 
            _db?.CloseSharedConnection();
            _db = null;
        }
 
        public static AsyncReader<T> Empty()
            => new AsyncReader<T>();
    }
#endif
}