Skip to content

Commit

Permalink
为了提升性能,在同步调用异步时规避卡UI上下文,所有await状态机都设置ConfigureAwait(false),开启CA2007并视…
Browse files Browse the repository at this point in the history
…为编译错误
  • Loading branch information
nnhy committed Nov 30, 2024
1 parent 2d9e22b commit 9164177
Show file tree
Hide file tree
Showing 14 changed files with 46 additions and 44 deletions.
2 changes: 1 addition & 1 deletion XCode/DataAccessLayer/Common/DbBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -393,7 +393,7 @@ public virtual async Task<DbConnection> OpenConnectionAsync()

var conn = Factory.CreateConnection();
conn.ConnectionString = GetConnectionString();
await conn.OpenAsync();
await conn.OpenAsync().ConfigureAwait(false);

return conn;
}
Expand Down
14 changes: 7 additions & 7 deletions XCode/DataAccessLayer/Common/DbSession.cs
Original file line number Diff line number Diff line change
Expand Up @@ -157,8 +157,8 @@ public virtual async Task<TResult> ProcessAsync<TResult>(Func<DbConnection, Task
{
try
{
using var conn = await Database.OpenConnectionAsync();
return await callback(conn);
using var conn = await Database.OpenConnectionAsync().ConfigureAwait(false);
return await callback(conn).ConfigureAwait(false);
}
catch (Exception ex)
{
Expand Down Expand Up @@ -194,7 +194,7 @@ public virtual async Task<TResult> ProcessAsync<TResult>(Func<Task<TResult>> cal
{
try
{
return await callback();
return await callback().ConfigureAwait(false);
}
catch (Exception ex)
{
Expand Down Expand Up @@ -584,9 +584,9 @@ public virtual Task<DbTable> QueryAsync(String sql, IDataParameter[]? ps)
using var cmd = OnCreateCommand(sql, CommandType.Text, ps);
return ExecuteAsync(cmd, true, async cmd2 =>
{
using var dr = await cmd2.ExecuteReaderAsync();
using var dr = await cmd2.ExecuteReaderAsync().ConfigureAwait(false);
var dt = new DbTable();
await dt.ReadAsync(dr);
await dt.ReadAsync(dr).ConfigureAwait(false);
return dt;
});
}
Expand Down Expand Up @@ -650,7 +650,7 @@ public virtual Task<Int64> InsertAndGetIdentityAsync(String sql, CommandType typ

return ExecuteAsync(cmd, false, async cmd2 =>
{
var rs = await cmd.ExecuteScalarAsync();
var rs = await cmd.ExecuteScalarAsync().ConfigureAwait(false);
if (rs == null || rs == DBNull.Value) return 0;

return Reflect.ChangeType<Int64>(rs);
Expand All @@ -668,7 +668,7 @@ public virtual Task<Int64> InsertAndGetIdentityAsync(String sql, CommandType typ
using var cmd = OnCreateCommand(sql, type, ps);
return ExecuteAsync(cmd, true, async cmd2 =>
{
var rs = await cmd.ExecuteScalarAsync();
var rs = await cmd.ExecuteScalarAsync().ConfigureAwait(false);
if (rs == null || rs == DBNull.Value) return default;
if (rs is T t) return t;

Expand Down
8 changes: 4 additions & 4 deletions XCode/DataAccessLayer/DAL_DbOperate.cs
Original file line number Diff line number Diff line change
Expand Up @@ -484,7 +484,7 @@ private async Task<TResult> QueryAsyncWrap<T1, T2, T3, TResult>(T1 k1, T2 k2, T3
// 读写分离
if (Strategy != null && Strategy.TryGet(this, k1 + "", action, out var rd) && rd != null)
{
return await rd.QueryAsyncWrap(k1, k2, k3, callback, action);
return await rd.QueryAsyncWrap(k1, k2, k3, callback, action).ConfigureAwait(false);
}

//CheckDatabase();
Expand All @@ -509,7 +509,7 @@ private async Task<TResult> QueryAsyncWrap<T1, T2, T3, TResult>(T1 k1, T2 k2, T3
}

Interlocked.Increment(ref _QueryTimes);
var rs = await InvokeAsync(AsyncSession, k1, k2, k3, callback, action);
var rs = await InvokeAsync(AsyncSession, k1, k2, k3, callback, action).ConfigureAwait(false);

cache?.Set(key, rs, Expire);

Expand All @@ -525,7 +525,7 @@ private async Task<TResult> ExecuteAsyncWrap<T1, T2, T3, TResult>(T1 k1, T2 k2,

//CheckDatabase();

var rs = await InvokeAsync(AsyncSession, k1, k2, k3, callback, action);
var rs = await InvokeAsync(AsyncSession, k1, k2, k3, callback, action).ConfigureAwait(false);

GetCache()?.Clear();

Expand Down Expand Up @@ -554,7 +554,7 @@ private async Task<TResult> InvokeAsync<T1, T2, T3, TResult>(IAsyncDbSession ses
using var span = tracer?.NewSpan(traceName, sql);
try
{
var rs = await callback(session, k1, k2, k3);
var rs = await callback(session, k1, k2, k3).ConfigureAwait(false);
AppendTag(span, sql, rs, action);

return rs;
Expand Down
4 changes: 2 additions & 2 deletions XCode/DataAccessLayer/DAL_Mapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ public async Task<IEnumerable<T>> QueryAsync<T>(String sql, Object? param = null
{
if (IsValueTuple(typeof(T))) throw new InvalidOperationException($"不支持ValueTuple类型[{typeof(T).FullName}]");

var dt = await QueryAsyncWrap(sql, param, "", (ss, s, p, k3) => ss.QueryAsync(s, Db.CreateParameters(p)), nameof(QueryAsync));
var dt = await QueryAsyncWrap(sql, param, "", (ss, s, p, k3) => ss.QueryAsync(s, Db.CreateParameters(p)), nameof(QueryAsync)).ConfigureAwait(false);

// 优先特殊处理基础类型,选择第一字段
var type = typeof(T);
Expand All @@ -121,7 +121,7 @@ public async Task<IEnumerable<T>> QueryAsync<T>(String sql, Object? param = null
/// <param name="sql">Sql语句</param>
/// <param name="param">参数对象</param>
/// <returns></returns>
public async Task<T> QuerySingleAsync<T>(String sql, Object? param = null) => (await QueryAsync<T>(sql, param)).FirstOrDefault();
public async Task<T> QuerySingleAsync<T>(String sql, Object? param = null) => (await QueryAsync<T>(sql, param).ConfigureAwait(false)).FirstOrDefault();

private static Boolean IsValueTuple(Type type)
{
Expand Down
4 changes: 2 additions & 2 deletions XCode/DataAccessLayer/Database/DB2.cs
Original file line number Diff line number Diff line change
Expand Up @@ -366,12 +366,12 @@ public override async Task<Int64> InsertAndGetIdentityAsync(String sql, CommandT
BeginTransaction(IsolationLevel.Serializable);
try
{
Int64 rs = await ExecuteAsync(sql, type, ps);
Int64 rs = await ExecuteAsync(sql, type, ps).ConfigureAwait(false);
if (rs > 0)
{
var m = reg_SEQ.Match(sql);
if (m != null && m.Success && m.Groups != null && m.Groups.Count > 0)
rs = await ExecuteScalarAsync<Int64>($"Select {m.Groups[1].Value}.currval From dual");
rs = await ExecuteScalarAsync<Int64>($"Select {m.Groups[1].Value}.currval From dual").ConfigureAwait(false);
}
Commit();
return rs;
Expand Down
6 changes: 3 additions & 3 deletions XCode/DataAccessLayer/Database/DaMeng.cs
Original file line number Diff line number Diff line change
Expand Up @@ -249,14 +249,14 @@ public override async Task<Int64> InsertAndGetIdentityAsync(String sql, CommandT
BeginTransaction(IsolationLevel.Serializable);
try
{
Int64 rs = await ExecuteAsync(sql, type, ps);
Int64 rs = await ExecuteAsync(sql, type, ps).ConfigureAwait(false);
if (rs > 0)
{
var m = reg_SEQ.Match(sql);
if (m != null && m.Success && m.Groups != null && m.Groups.Count > 0)
rs = await ExecuteScalarAsync<Int64>($"Select {m.Groups[1].Value}.currval From dual");
rs = await ExecuteScalarAsync<Int64>($"Select {m.Groups[1].Value}.currval From dual").ConfigureAwait(false);
else
rs = await ExecuteScalarAsync<Int64>("Select @@Identity");
rs = await ExecuteScalarAsync<Int64>("Select @@Identity").ConfigureAwait(false);
}
Commit();
return rs;
Expand Down
8 changes: 4 additions & 4 deletions XCode/DataAccessLayer/Database/Oracle.cs
Original file line number Diff line number Diff line change
Expand Up @@ -484,10 +484,10 @@ public override Task<DbTable> QueryAsync(String sql, IDataParameter[]? ps)
using var cmd = OnCreateCommand(sql, CommandType.Text, ps);
return ExecuteAsync(cmd, true, async cmd2 =>
{
using var dr = await cmd2.ExecuteReaderAsync();
using var dr = await cmd2.ExecuteReaderAsync().ConfigureAwait(false);
var dt = new DbTable();
dt.ReadHeader(dr);
await dt.ReadDataAsync(dr, GetFields(dt, dr));
await dt.ReadDataAsync(dr, GetFields(dt, dr)).ConfigureAwait(false);
return dt;
});
}
Expand All @@ -497,12 +497,12 @@ public override async Task<Int64> InsertAndGetIdentityAsync(String sql, CommandT
BeginTransaction(IsolationLevel.Serializable);
try
{
Int64 rs = await ExecuteAsync(sql, type, ps);
Int64 rs = await ExecuteAsync(sql, type, ps).ConfigureAwait(false);
if (rs > 0)
{
var m = reg_SEQ.Match(sql);
if (m != null && m.Success && m.Groups != null && m.Groups.Count > 0)
rs = await ExecuteScalarAsync<Int64>($"Select {m.Groups[1].Value}.currval From dual");
rs = await ExecuteScalarAsync<Int64>($"Select {m.Groups[1].Value}.currval From dual").ConfigureAwait(false);
}
Commit();
return rs;
Expand Down
2 changes: 1 addition & 1 deletion XCode/DataAccessLayer/DbPackage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -725,7 +725,7 @@ protected override async Task ReceiveAsync(ActorContext context, CancellationTok
else
dt.WriteData(bn);

await Stream.FlushAsync();
await Stream.FlushAsync(cancellationToken).ConfigureAwait(false);
}
}

Expand Down
24 changes: 12 additions & 12 deletions XCode/Entity/Entity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1156,7 +1156,7 @@ public static DbTable FindData(Expression where, String order, String selects, I
// 优待主键查询
if (where is FieldExpression fe && fe.Field != null && fe.Field.PrimaryKey) max = 0;

var list = await FindAllAsync(where, null, null, 0, max);
var list = await FindAllAsync(where, null, null, 0, max).ConfigureAwait(false);
return list.Count <= 0 ? null : list[0];
}

Expand Down Expand Up @@ -1257,7 +1257,7 @@ public static async Task<IList<TEntity>> FindAllAsync(Expression where, String?

var start = (Int32)(count - (startRowIndex + maximumRows));
var builder2 = CreateBuilder(where, order2, selects);
var list = LoadData(await session.QueryAsync(builder2, start, max));
var list = LoadData(await session.QueryAsync(builder2, start, max).ConfigureAwait(false));
if (list.Count <= 0) return list;

// 如果正在使用单对象缓存,则批量进入
Expand All @@ -1276,7 +1276,7 @@ public static async Task<IList<TEntity>> FindAllAsync(Expression where, String?
if (shards == null || shards.Length == 0)
{
var builder = CreateBuilder(where, order, selects);
var list2 = LoadData(await session.QueryAsync(builder, startRowIndex, maximumRows));
var list2 = LoadData(await session.QueryAsync(builder, startRowIndex, maximumRows).ConfigureAwait(false));

// 如果正在使用单对象缓存,则批量进入
if (selects.IsNullOrEmpty() || selects == "*") LoadSingleCache(list2);
Expand Down Expand Up @@ -1307,15 +1307,15 @@ public static async Task<IList<TEntity>> FindAllAsync(Expression where, String?

var builder = CreateBuilder(where, order, selects);
builder.Table = session.FormatedTableName;
var list2 = LoadData(await session.QueryAsync(builder, row, max));
var list2 = LoadData(await session.QueryAsync(builder, row, max).ConfigureAwait(false));
if (list2.Count > 0) rs.AddRange(list2);

// 总数已满足要求,返回
if (maximumRows > 0 && rs.Count >= maximumRows) return rs;

// 避免最后一张表没有查询到相关数据还继续进行查询,减少不必要查询
var skipCount = 0;
if (i < shards.Length) skipCount = (Int32)await session.QueryCountAsync(builder);
if (i < shards.Length) skipCount = (Int32)await session.QueryCountAsync(builder).ConfigureAwait(false);

max -= list2.Count;
// 后边表索引记录数应该是减去前张表查询出来的记录总数,有可能负数
Expand All @@ -1334,7 +1334,7 @@ public static async Task<IList<TEntity>> FindAllAsync(Expression where, String?
/// <returns></returns>
public static async Task<IList<TEntity>> FindAllAsync(Expression where, PageParameter? page = null, String? selects = null)
{
if (page == null) return await FindAllAsync(where, null, selects, 0, 0);
if (page == null) return await FindAllAsync(where, null, selects, 0, 0).ConfigureAwait(false);

// 页面参数携带进来的扩展查询
if (page.State is Expression exp)
Expand All @@ -1355,7 +1355,7 @@ public static async Task<IList<TEntity>> FindAllAsync(Expression where, PagePara
if (where.IsEmpty && session.LongCount > 100_000)
rows = session.LongCount;
else
rows = await FindCountAsync(where, null, selects, 0, 0);
rows = await FindCountAsync(where, null, selects, 0, 0).ConfigureAwait(false);
if (rows <= 0) return new List<TEntity>();

page.TotalCount = rows;
Expand All @@ -1367,9 +1367,9 @@ public static async Task<IList<TEntity>> FindAllAsync(Expression where, PagePara
// 采用起始行还是分页
IList<TEntity> list;
if (page.StartRow >= 0)
list = await FindAllAsync(where, orderby, selects, page.StartRow, page.PageSize);
list = await FindAllAsync(where, orderby, selects, page.StartRow, page.PageSize).ConfigureAwait(false);
else
list = await FindAllAsync(where, orderby, selects, (page.PageIndex - 1) * page.PageSize, page.PageSize);
list = await FindAllAsync(where, orderby, selects, (page.PageIndex - 1) * page.PageSize, page.PageSize).ConfigureAwait(false);

if (list.Count == 0) return list;

Expand All @@ -1380,7 +1380,7 @@ public static async Task<IList<TEntity>> FindAllAsync(Expression where, PagePara
)
{
var selectStat = Meta.Factory.SelectStat;
if (!selectStat.IsNullOrEmpty()) page.State = (await FindAllAsync(where, null, selectStat)).FirstOrDefault();
if (!selectStat.IsNullOrEmpty()) page.State = (await FindAllAsync(where, null, selectStat).ConfigureAwait(false)).FirstOrDefault();
}

return list;
Expand Down Expand Up @@ -1421,7 +1421,7 @@ public static async Task<Int64> FindCountAsync(Expression where, String? order =

// 自动分表
var shards = Meta.InShard || where == null ? null : Meta.ShardPolicy?.Shards(where);
if (shards == null || shards.Length == 0) return await session.QueryCountAsync(builder);
if (shards == null || shards.Length == 0) return await session.QueryCountAsync(builder).ConfigureAwait(false);

var rs = 0L;
foreach (var shard in shards)
Expand All @@ -1435,7 +1435,7 @@ public static async Task<Int64> FindCountAsync(Expression where, String? order =

session = EntitySession<TEntity>.Create(connName, tableName);
builder.Table = session.FormatedTableName;
rs += await session.QueryCountAsync(builder);
rs += await session.QueryCountAsync(builder).ConfigureAwait(false);
}
return rs;
}
Expand Down
2 changes: 1 addition & 1 deletion XCode/Entity/EntityFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ public static async Task InitAllAsync()
if (span != null) span.Value++;
}

await Task.WhenAll(ts);
await Task.WhenAll(ts).ConfigureAwait(false);
}
catch (Exception ex)
{
Expand Down
2 changes: 1 addition & 1 deletion XCode/Entity/EntitySession.cs
Original file line number Diff line number Diff line change
Expand Up @@ -899,7 +899,7 @@ public virtual async Task<Int32> InsertAsync(IEntity entity)
{
if (DataTable.IsView) throw new NotSupportedException("视图无法添删改!");

var rs = await Factory.Persistence.InsertAsync(this, entity);
var rs = await Factory.Persistence.InsertAsync(this, entity).ConfigureAwait(false);

var e = entity as TEntity;

Expand Down
8 changes: 4 additions & 4 deletions XCode/Entity/IEntityPersistence.cs
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ public virtual async Task<Int32> InsertAsync(IEntitySession session, IEntity ent
var bAllow = factory.AllowInsertIdentity;
if (field != null && field.IsIdentity && !bAllow && factory.AutoIdentity)
{
var id = await session.InsertAndGetIdentityAsync(sql, CommandType.Text, dps);
var id = await session.InsertAndGetIdentityAsync(sql, CommandType.Text, dps).ConfigureAwait(false);
if (id > 0) entity[field.Name] = id;
rs = id > 0 ? 1 : 0;
}
Expand All @@ -279,7 +279,7 @@ public virtual async Task<Int32> InsertAsync(IEntitySession session, IEntity ent
if (bAllow) sql = $"SET IDENTITY_INSERT {session.FormatedTableName} ON;{sql};SET IDENTITY_INSERT {session.FormatedTableName} OFF";
}
}
rs = await session.ExecuteAsync(sql, CommandType.Text, dps);
rs = await session.ExecuteAsync(sql, CommandType.Text, dps).ConfigureAwait(false);
}

// 清除脏数据,避免连续两次调用Save造成重复提交
Expand Down Expand Up @@ -312,7 +312,7 @@ public virtual async Task<Int32> UpdateAsync(IEntitySession session, IEntity ent
entity.Dirtys.Clear();
}

var rs = await session.ExecuteAsync(sql, CommandType.Text, dps);
var rs = await session.ExecuteAsync(sql, CommandType.Text, dps).ConfigureAwait(false);

//EntityAddition.ClearValues(entity as EntityBase);

Expand All @@ -329,7 +329,7 @@ public virtual async Task<Int32> DeleteAsync(IEntitySession session, IEntity ent
var sql = SQL(session, entity, DataObjectMethodType.Delete, ref dps);
if (sql.IsNullOrEmpty()) return 0;

var rs = await session.ExecuteAsync(sql, CommandType.Text, dps);
var rs = await session.ExecuteAsync(sql, CommandType.Text, dps).ConfigureAwait(false);

// 清除脏数据,避免重复提交保存
entity.Dirtys.Clear();
Expand Down
4 changes: 3 additions & 1 deletion XCode/XCode.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
<SignAssembly>True</SignAssembly>
<AssemblyOriginatorKeyFile>..\Doc\newlife.snk</AssemblyOriginatorKeyFile>
<NoWarn>1701;1702;NU5104;NETSDK1138;CS7035</NoWarn>
<AnalysisLevel>latest</AnalysisLevel>
<WarningsAsErrors>CA2007</WarningsAsErrors>
</PropertyGroup>
<PropertyGroup>
<PackageId>NewLife.XCode</PackageId>
Expand All @@ -44,7 +46,7 @@
</PackageReference>
</ItemGroup>
<ItemGroup>
<PackageReference Include="NewLife.Core" Version="11.0.2024.1124-beta1518" />
<PackageReference Include="NewLife.Core" Version="11.0.2024.1130-beta0449" />
</ItemGroup>
<ItemGroup>
<Compile Remove="build\**" />
Expand Down
2 changes: 1 addition & 1 deletion XUnitTest.XCode/XUnitTest.XCode.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
<PackageReference Include="NewLife.Core" Version="11.0.2024.1124-beta1518" />
<PackageReference Include="NewLife.Core" Version="11.0.2024.1130-beta0449" />
<PackageReference Include="NewLife.IP" Version="2.2.2024.1102" />
<PackageReference Include="NewLife.UnitTest" Version="1.0.2024.1006" />
<PackageReference Include="System.Diagnostics.PerformanceCounter" Version="9.0.0" />
Expand Down

0 comments on commit 9164177

Please sign in to comment.