views:

55

answers:

2

Hi,

Is this code considered thread safe even though multiple threads may be polling the directory for files on the webserver at once?

Thanks, Mike

    //Get a testimonial
    virtualRoot = HostingEnvironment.ApplicationVirtualPath;
    configuration = WebConfigurationManager.OpenWebConfiguration(virtualRoot);
    pathToNewsDirectory = configuration.AppSettings.Settings["VanHinoWeb.news.dir"].Value;
    fileListing = Directory.GetFiles(pathToNewsDirectory, "*xml");
    int index = generator.Next(0, fileListing.Length);

    //Put it into XML and get data into string array to return
    testimonialReader = new XmlTextReader(fileListing[index]);
    testimonialReader.ReadToFollowing("quote");
    testimonialData[0] = testimonialReader.ReadString();
    testimonialReader.ReadToFollowing("author");
    testimonialData[1] = testimonialReader.ReadString();
    testimonialReader.ReadToFollowing("authorTitle");
    testimonialData[2] = testimonialReader.ReadString();

    return testimonialData;
}
+1  A: 

Most of the calls under the Get a testimonial comment should be thread safe. Accessing the hosting environment, app settings, and listing directory contents should be fine.

However, it's unclear where the generator object, testimonialReader, and testimonialData objects are created and whether they are shared across threads or not. If they are shared across threads, then the code is not thread safe.

LBushkin
I should also mention that all the objects used in this method are declared within the method. Therefor I thought that each thread will have its own stack of objects.
Mike
Then you should be fine.
LBushkin
+1  A: 

As you are only reading files it looks that this is thread safe. Also you need to close the XmlTextReader (testimonialReader) after you are finished using it.

Darin Dimitrov