Click here to Skip to main content
15,887,746 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi,
I have a requirement to do some time consuming operation(to create a html template based on the request) in Web Api and convert it as a pdf and send as attachment in mail.This has to happen as a background job.
The problem is I have a query handler which is an async method and this method is used to create multiple templates and is very much time consuming and we don't want the user to wait till we complete this operation. So we have decided to use HangFire.
But the problem here is the job is not executing and in most of the forums they have mentioned that only synchronous calls can be done using HangFire.

So I wanted to know whether is it possible to call the asynchronous method synchronously, so that I will call this synchronous method inside backgroundJob.Enqueue().If so can you please help me with some example.
Note: I am doing further operations based on the result of that async method

What I have tried:

I tried calling the method asynchronous method synchronously using
C#
Task.Run(()=>AsyncMethod()).Result
and also tried
C#
Task.Run(async()=>await AsyncMethod()).Result, Task.Run(()=>AsyncMethod()).ConfigureAwait(false).GetAwaiter().GetResult()
like,

C#
public void HangFireMethodCall(){
BackgroundJob.Enqueue(()=>SyncMethod());
}

public SomeReturnType SyncMethod(){
Task.Run(async()=>await AsyncMethod(Request)).Result;
return successMessage;
}

public async Task<returntype> AsyncMethod(RequestType request){
var response= await ExecuteAsync(request);
//Based on response do some operation
}
But nothing executed the async method.

few referral links I have tried are,
Async task jobs - question - Hangfire Discussion[^]
async await - How to call asynchronous method from synchronous method in C#? - Stack Overflow[^]
Posted
Updated 29-Oct-19 10:18am
v5

1 solution

Both of your links are several years old; Hangfire did add in some quasi-synchronous methods with the release of version 1.6:
Hangfire 1.6.0[^]

Please note this paragraph though:
Hangfire 1.6.0 Blog Entry:
That’s not a real asynchrony
Please consider this feature as a syntactic sugar. Background processing hasn’t became asynchronous. Internally it was implemented using the Task.Wait method, so workers don’t perform any processing, while waiting for a task completion. Real asynchrony may come in Hangfire 2.0 only, and it requires a lot of breaking changes to the existing types.
And then there is this SO entry (which led me to the above)
c# - How to invoke async methods in Hangfire? - Stack Overflow[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900