Hi All,
Am using Hangfire to do some background work in my app, this is my scenarios.
- ASP.Net MVC application, calling Business layer,
- Business layer calling a method(Data access layer), it takes some time to get data from.
- Meanwhile I won’t wait for a response, so I decide to move next action to execute, here used hangfire concepts(JobCancellationToken)
- In some time after I wanna cancel requested call
- I able to cancel I seen backend mapped table([HangFire].[State] Name) been updated as Deleted.
- But requested call processing not terminated()
Note:( requested call still processing in background like DB still handle request)
Example : In my query has some insert statement to insert some data’s into some other tables. while interrupted process not stopped, it keep on insert until the whole request.
Exampel Code
- Main process start.
BackgroundJobJobMain()
{
try
{
GlobalConfiguration.Configuration.UseSqlServerStorage("connection string");
using (var server = new BackgroundJobServer())
{
var tempJobId = BackgroundJob.Enqueue(() =>StartNewBackgroundJob(JobCancellationToken.Null));
// In Database i can see JibId => Enqueued
// Wait for some time and want to cancel job.
Thread.Sleep(5000);
DeleteJob(tempJobId );
// In Database i can see JibId => Deleted
//But in flat file it not stoped imediate, it fully write all iteration content, like 1,2,3,4,5,6,7,8,9 for every requet.
}
}
catch (Exception ex)
{
throw;
}
}
StartNewBackgroundJob(IJobCancellationToken cancelationToken)
{
try
{
ContentWriting();
// In Database i can see JibId => Processing
}
catch (Exception ex)
{
throw;
}
return string.Empty;
}
// To write some content into flat file.
ContentWriting()
{
int iteration = 0;
for (; iteration < 10; iteration++)
{
//Insert logic for some table's
//.....................
//--------------
Thread.Sleep(1000); //wait for a minute
}
}
- Delete job
public bool DeleteJob(string jobId)
{
BackgroundJob.Delete(jobId);
return false;
}