Viachslau
Viachslau

Reputation: 361

BackgroundAgent ReaderWriterLockSlim synchronization

I'm trying to synchronize access to IsolatedStorage between foreground and BackgroundAgent. The problem is that when I enter the lock I Have one thread, but after awaiting in storage access, the thread is the other one and I get SynchronizationLockException. Does anybody know the way to solve the problem. Why are the threads different in the first place? Thanks

Upvotes: 0

Views: 35

Answers (2)

Soonts
Soonts

Reputation: 21966

Background agents work in a separate process.

You can't use SemaphoreSlim because you need a named synchronization primitive to synchronize two processes. When I did what you’re doing, I used a named Mutex instance + blocking file IO API that happens in a single thread, but I only needed to write a few kilobytes max.

If you need to concurrently write large files, you can write them asynchronously into a temp file, then wait for the mutex, rename the temp file to the destination file name, then release the mutex.

Upvotes: 0

Stephen Cleary
Stephen Cleary

Reputation: 457422

You can't use thread-affine locks with async code. With async code on background threads, any thread pool thread may resume the async method. It's not any better with UI threads either; after an await, you will resume on the UI thread, but any arbitrary code runs in the meantime, which completely defeats the purpose of a lock.

I recommend you use SemaphoreSlim instead.

Upvotes: 1

Related Questions