我正尝试使用以下代码每秒从数据库读取数据:
public class DBChangeService : DelegatingHandler, IHostedService
{
private Timer _timer;
public SqlDependencyEx _sqlDependency;
private readonly IHubContext<SignalServer> _hubcontext;
private readonly IServiceScopeFactory _scopeFactory;
string connectionString = "";
public IConfiguration Configuration { get; }
public DBChangeService(IConfiguration configuration, IHubContext<SignalServer> hubcontext, IServiceScopeFactory scopeFactory)
{
_scopeFactory = scopeFactory;
_hubcontext = hubcontext;
Configuration = configuration;
connectionString = Configuration.GetConnectionString("DefaultConnection");
}
public Task StartAsync(CancellationToken cancellationToken)
{
_timer = new Timer(Heartbeat, null, 0, 1000);
return Task.CompletedTask;
}
public void Heartbeat(object state)
{
_hubcontext.Clients.All.SendAsync("SBSystemBrodcasting", SBSystemApps());
}
public async Task<List<SomeModel>> SBSystemApps()
{
var data = new List<SomeModel>();
using (var scope = _scopeFactory.CreateScope())
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
string commandText = @"SELECT
a.name as AppName,
a.state as AppState,
a.created_at as AppCreatedAt,
a.updated_at as AppUpdatedAt,
a.foundation as AppFoundation,
s.name as SpaceName,
o.name as OrgName
FROM
apps as a
INNER JOIN
spaces as s ON a.space_guid = s.space_guid
INNER JOIN
organizations as o ON s.org_guid = o.org_guid
where s.name = 'system' and o.name = 'system' and a.foundation = 2";
try
{
SqlCommand cmd = new SqlCommand(commandText, connection);
await connection.OpenAsync();
using (DbDataReader reader = await cmd.ExecuteReaderAsync())
{
while (await reader.ReadAsync())
{
var sqlresult = new SomeModel
{
AppName = reader["AppName"].ToString(),
AppState = reader["AppState"].ToString(),
AppCreatedAt = Convert.ToDateTime(reader["AppCreatedAt"]),
AppUpdatedAt = Convert.ToDateTime(reader["AppUpdatedAt"]),
AppFoundation = Convert.ToInt32(reader["AppFoundation"]),
SpaceName = reader["SpaceName"].ToString(),
OrgName = reader["OrgName"].ToString(),
};
data.Add(sqlresult);
}
}
}
finally
{
connection.Close();
}
return data;
}
}
}
public Task StopAsync(CancellationToken cancellationToken)
{
//Timer does not have a stop.
_timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask;
}
}
出现以下错误:
Newtonsoft.Json.JsonSerializationException:自引用循环 检测到类型为“任务”的属性 'System.Runtime.CompilerServices.AsyncTaskMethodBuilder
1+AsyncStateMachineBox
1 [System.Collections.Generic.List`1 [TestApp.Models.SomeModel],TestApp.Services.DBChangeService + d__11]'。
我已经尝试了我可以在StackOverflow上找到的几乎所有可能的解决方案,但是都无法正常工作
在启动时:
services.AddMvc().AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
在班级标题上,我尝试使用[JsonObject(IsReference = true)]
,但是没有任何想法对我有用吗?
型号:
[JsonObject(IsReference = true)]
public partial class SomeModel
{
public string AppName { get; set; }
public string AppState { get; set; }
public DateTime AppCreatedAt { get; set; }
public DateTime AppUpdatedAt { get; set; }
public int AppFoundation { get; set; }
public string OrgName { get; set; }
public string SpaceName { get; set; }
}
答案 0 :(得分:3)
_hubcontext.Clients.All.SendAsync("SBSystemBrodcasting", SBSystemApps());
问题是您正在使用SendAsync
来调用Task
。这不是设计使用API的方式。您应该通过要使用的实际有效载荷。
有多种解决方法。一种是使用:
_hubcontext.Clients.All.SendAsync("SBSystemBrodcasting", SBSystemApps().GetAwaiter().GetResult());
尽管我建议阅读this guidance,以了解为什么它不是一个好主意。
另一种方法是更改SBSystemApps
使其同步(即返回List<T>
而不是Task<List<T>>
。