Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AsyncLocal<T> retains values on every job run #2409

Open
djdd87 opened this issue May 24, 2024 · 2 comments
Open

AsyncLocal<T> retains values on every job run #2409

djdd87 opened this issue May 24, 2024 · 2 comments

Comments

@djdd87
Copy link

djdd87 commented May 24, 2024

I implemented AsyncLocal in a particular service method to avoid some repeated processing, however the same service method ends up being called by Hangfire and on every job run the data of AsyncLocal.Value, which should be null on each asynchronous call retains the same value until the app is retarted. The code works perfectly when coming from a SignalR or WebAPI request, it's only Hangfire processes that retain the value.

Code for job setup:

RecurringJobManager manager = new RecurringJobManager();
if (jobEnable)
{
    manager.AddOrUpdate("JobName", Job.FromExpression(() => TaskSchedulingController.DoJob()), "* * * * *", options);
}
else
{
    manager.RemoveIfExists("JobName");
}

Code example for job, which will only ever run successfully once, then will error on every subsequent call:

private static AsyncLocal<string> _test = new AsyncLocal<string>();

public async Task DoJob()
{
	if (_test.Value != null)
	{
		throw new Exception("AsyncLocal is retaining a value");
	}
	_test.Value = "ABC123";
}
@odinserj
Copy link
Member

While I agree that AsyncLocal instances shouldn't be preserved across different background job runs, and ExecutionContext should be somehow flushed, but this is potentially a breaking change for those who use this feature. So I'm postponing this to 2.0 version without any specific point in time.

Is it possible to clean these values manually, for example in a try/finally block?

@djdd87
Copy link
Author

djdd87 commented Jun 3, 2024

Yeah, that's actually how I worked around the issue for the time being.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

No branches or pull requests

2 participants