Multiple tasks cause exception "cannot access file because it is being used by another process" RRS feed

  • Question

  • Hi,

    I have created a windows service, and I am creating parallel tasks to access users inbox (impersonate). Each task will establish its own connection to the exchange server. We are going to run a maximum of 5 tasks at a time (impersonating 5 mailboxes). When I start the first task, everything runs fine, but when I start the second task, the service throws an unhandled exception. If I only start one task, everything functions correctly.

    Each task starts a sync on folder items, and when all the items have been synced the task will shut down. That is the goal.

    I have reorganized my code several times to ensure there is not any contention. But I always get an file access error in different locations. 

    I read the following article, and it states that as long as we create the service in a separate thread we should be ok.

    Any suggestions?

    Thanks, Tom

    Wednesday, August 22, 2018 4:58 PM

All replies

  • >>Multiple tasks cause exception "cannot access file because it is being used by another process"

    If that is the error your getting then that isn't an Exchange or EWS error, sounds like you have some issue in non Exchange parts of the code. I would look at anything that is using a File (or Stream) like logging or if you writing the results to file.


    Wednesday, August 22, 2018 11:37 PM
  • Hi Glen,

    Thanks for responding. I commented out all of the logging code, which is the usual culprit for problems. 

    I create a few tasks, create the ExchangeService in each task, but I wind up getting the same error.

    It throws an exception on the following line.

    public void GetMailFolders(ExchangeService svr, WellKnownFolderName fldr) {

    Folder rootInboxFolder = Folder.Bind(svr, fldr); }

    The exception ends up in the web request logic (protected IEwsHttpWebRequest BuildEwsHttpWebRequest) and complains that this file is in use by another process. Which blantly tells me there is a bad issue with multithreading.

    I have observed people on the web putting locks around the call to bind and other types of logic to avoid issues. But I believe that to be a band-aid for a synchronization issue.

    Thursday, August 23, 2018 3:50 PM
  • Do you have tracing enabled ? something doesn't sound right to me there should be no files involved as it just uses HttpwebRequest under the covers. The EWS Managed API is open source so unless you have something really basic in your own code that is doing you'll need to delve into the source to try to debug it further. 
    Thursday, August 23, 2018 11:32 PM