[英]How to synchronously call async method from quartz schedule job
I am trying to call a webapi method from my quartz.net schedule job.我正在尝试从我的 quartz.net 计划作业中调用 webapi 方法。 I am not sure whether the way I am doing is right?我不确定我的做法是否正确? Can anyone help if this is the right way or is there any better approach available?如果这是正确的方法或有更好的方法可用,任何人都可以提供帮助吗?
MethodRepository.cs方法库.cs
public async Task<IEnumerable<ResultClass>> GetResult(string queryCriteria)
{
return await _httpClient.Get(queryCriteria);
}
Quartz job:石英作业:
public async void Execute(IJobExecutionContext context)
{
var results= await _repo.GetResult();
}
generic Httpclient :通用 Httpclient :
public async Task<IEnumerable<T>> Get(string queryCriteria)
{
_addressSuffix = _addressSuffix + queryCriteria;
var responseMessage = await _httpClient.GetAsync(_addressSuffix);
responseMessage.EnsureSuccessStatusCode();
return await responseMessage.Content.ReadAsAsync<IEnumerable<T>>();
}
But the quartz documentation says I can't use async method in a quartz job.但是石英文档说我不能在石英工作中使用异步方法。 How can one the Web API method then?那么如何使用 Web API 方法呢?
Can I change the quartz job execute method as:我可以将石英作业执行方法更改为:
public void Execute(IJobExecutionContext context)
{
var result = _repo.GetResult().Result;
}
Quartz.NET 3.0 supports async/await out of the box. Quartz.NET 3.0支持开箱即用的 async/await。 So you can (and must) now declare Execute method as Task returning and you can use async/await.因此,您现在可以(并且必须)将 Execute 方法声明为 Task 返回,并且可以使用 async/await。
public async Task Execute(IJobExecutionContext context)
{
var result = await _repo.GetResult();
}
If you have to do it - then yes you can do that, but it will block the calling thread until the asynchronous operation is complete.如果你必须这样做 - 那么是的,你可以这样做,但它会阻塞调用线程,直到异步操作完成。
Task.Result will wrap any exception into an AggregateException. Task.Result会将任何异常包装到 AggregateException 中。
So you should probably put your httpclient call in a try catch.所以你可能应该把你的 httpclient 调用放在一个 try catch 中。
try
{
var result = _repo.GetResult().Result;
}
catch (AggregateException ae)
{
// handle exception
}
Also, it seems they are working on an AsyncJob .此外,他们似乎正在研究AsyncJob 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.