Thread-Safety is not an aspect of which I am very worried, because the simple applications and libraries that I wrote usually run only in the main thread or do not directly change the properties or fields in any classes that I need to worry about before.
However, I started working on a personal project that I use WebClient to asynchronously download data from a remote server. There is a Queue<Uri> that contains a pre-created URI series queue for loading data.
So, consider the following snippet (this is not my real code, but I hope this illustrates my question:
private WebClient webClient = new WebClient(); private Queue<Uri> requestQueue = new Queue<Uri>(); public Boolean DownloadNextASync() { if (webClient.IsBusy) return false; if (requestQueue.Count == 0) return false var uri = requestQueue.Dequeue(); webClient.DownloadDataASync(uri); return true; }
If I understand correctly, this method is not thread safe (assuming that this particular instance of this object is known to multiple threads). My reasoning with WebClient may become busy between the time that IsBusy and the DownloadDataASync() method is called. In addition, requestQueue can become empty between the Count check and when the next item is deleted.
My question is the best way to handle this type of situation in order to make it thread safe?
This is a more abstract question, because I understand for this particular method that there will be an extremely inconvenient moment for this to actually cause the problem, and to cover this case, I could just wrap the method in a suitable try-catch , since both parts threw an exception. But is there any other option? Can the lock statement apply here?
source share