Business case:
I have a ASMX web service
that copies/deletes/downloads files from some remote directory. My WebMethod
creates an instance of the business class that performs all these operations. In case of downloading, I check which file is the latest one and downloads it. Once downloaded, I want to delete it immediately. However, in multithreaded scenario, there is good possibility that the file I try to delete is already deleted by some other thread.
My solution:
To avoid such issues, I want to web service execute only one thread at a time. Any other calls to the WebMethod
should be waiting until previous thread completes the download and delete operation.
For this I have declared one static
variable in my business class. At the start of my business method (which is called from the WebMethod
) in the business class, I call the lock
on this static object. So other web service calls will not execute the code in the business method until the lock
on that static variable (object) is not released.
public class FileOperator
{
private static object locker = new object();
public void DownloadAndDeleteFile(string fileName)
{
lock(locker)
{
// All business logic goes here.
}
}
}
The code in the WebMethod
looks like this.
FileOperator fileOperator = new FileOperator();
fileOperator.DownloadAndDeleteFile("File1.txt");
Questions:
- Is my solution correct?
- If yes, how to allow only one thread to execute from within the web service? Please note that I want to do this only for Downloading.. Uploading should work in parallel threads..
- Any better solution?
I am using .NET 4.0.