Reputation: 822
I have a scenario in which I have to fetch xml file of customer from api call and then save it in my computer on first request and after that every request of that customer will use my computer file to get data of particular customer.
for example if I have two customers ABC and XYZ. let say first request come for ABC I want to start downloading file of ABC. while downloading is in progress let say first request of XYZ comes. I want to proceed downloading of XYZ customer file as well. but lets say while downloading is in progress for ABC and another request of ABC comes I should let it wait till file of ABC is downloading and after the file will be download I want to get data of 2nd request from that file.
I think about 2 solutions for eg if I lock code of downloading
// code
lock(obj)
{
DownloadXmle("ABC");
}
// code
2nd option is if I declare a static list and before downloading file i push customer number in that list and for all other requests of that customer it checks if institution number is in that list it should wait
//code
currentlyDownloadingFileList.add("ABC");
DownloadXmle("ABC");
currentlyDownloadingFileList.Remove("ABC");
//code
is there any better thing for that?
Upvotes: 0
Views: 166
Reputation: 663
To my mind it is better to use TPL. DownloadXmle
should be asynchronous method which is returning Task<T>
or just Task
. It will help you to have better resources utilization and will give you powerful tool for your task. Let's look at your method implementation in that case:
public async Task DownloadXmleAsync(string customer)
{
...
}
Next when you will call you method you should save returning task somewhere:
Task taskAbc = DownloadXmleAsync("ABC");
When you will get new request for this customer you should do next:
taskAbc = taskAbc.ContinueWith(prevTask => DownloadXmleAsync("ABC"));
ContinueWith will schedule your next call and will run it only after first request will be finished. Second task will run in any case. taskAbc
will be a link to a second task. Every time you will get new request it will scheduled.
Upvotes: 1
Reputation: 888185
You should use a ConcurrentDictionary<string, object>
to store a thread-safe map of customers to lock objects.
Use GetOrAdd()
to safely get a lock object for the customer, then lock on that object.
Upvotes: 1