Search code examples
c#backgroundworkeradd-inarcgisesri

ArcGIS add-in: creating shapefile in backgroundworker, can't display the result in the same ArcMap session


The add-in was initally wrote without using backgroundworker and it worked fine. I was able to create a shapefile which can be added and viewed immediately after the execution in the same ArcMap session.

Then I tried to add a progress bar to the UI which was not showing any change until the execution was complete. That's when I added a backgroundworker class and moved the time-consuming shapefile creation code (without any change) into the dowork event handler of the backgroundworker.

While this makes the UI much more responsive, if I add the result shapefile into the same ArcMap session, nothing shows up on the screen. ArcMap also reports a Drawing Error, saying "Cannot acquire a lock [the table xxx is being written by another process].

I'm sure the writing is complete at that point. And I can view the result without any problem if I close the current ArcMap session and start a new one.

There is too much code to post and I have a strong feeling the problem is caused by moving the code as is to the backgroundworker class. I hope you folks out there who's more experienced with backgroundworker/ArcGIS add-in can give me some pointers what could be the culprit. Thanks in advance!


Solution

  • I resolved the issue, however, not quite sure why it is the case.

    The backgroundworkder_DoWork() calls a function that uses a FeatureCursor in the way below:

    IFeatureCursor featureCursor = FeatureClass.Update(null,true);

    go through the features doing updates with the cursor

    if (certain condition) { featureCursor=FeatureClass.Update(null,true); go through the features again doing some additional updates }

    I found out that even if I run the Marshal.ReleaseComObject() method on featureCursor in the end, the write lock (".wr.lock") to the shapefile persists. However, if instead of re-using featureCursor I define and use a new cursor in the "if" clause, Marshal.ReleaseCombObject() method can remove the write lock. But then again, if a new cursor is defined and used, I don't need to use the release method. Although the ".wr.lock" file remains after the execution, I can add the output shapefile to the same ArcMap session and view it without any problem.

    Would appreciate it if someone can give insight on why the above code as is when placed in the UI thread didn't cause any issue, but when called by the backgroundworker_DoWork() runs into the lock issue.

    And also is it a bad habit to re-use a FeatureCcursor as I did in the code above?