c# - How do I prevent the creation of multiple background processes working on the same request? -
i have simple webapi controller method that's purpose trigger background processing , return 202 accepted response (without having completed background processing consistent 202 response.)
public async task<ihttpactionresult> dosomething(string id) { hostingenvironment.queuebackgroundworkitem(async ct => { //do work } return responsemessage(new httpresponsemessage(httpstatuscode.accepted)); }
however, want able prevent multiple requests same endpoint same id triggering multiple instances of same background processing simultaneously.
effectively, if 2 requests same id's made @ same time (or near enough), first 1 processing id , second 1 able identify , take action accordingly , not duplicate work that's being done.
i'd avoid databases/persistent storage if @ possible , i'm aware of risks of running async tasks within iis worker process - sake of argument, background processing not critical.
how can go doing this? appreciated.
you'll need kind of storage shared between possible workers. be, example:
- a static variable. easiest implement, has limitations when application not run in 1 appdomain (especially important if want scale). not best way
- an sql database: common one. if application uses one, i'd go route.
- a no-sql database, example key-value store. might alternative if application not use sql database yet.
- some external component such workflow management tool
edit: example using concurrentdictionary (per request of thread starter - stil think using (possibly nosql) database elegant way) - put tasks dictionary:
private concurrentdictionary<string, task<sometype>> _cache = new //... var task = _cache.getoradd("<key>", key => task.run(() => /*do work*/)); if (task.iscompleted) /*result ready*/; else /*have wait*/;
Comments
Post a Comment