|
-
Jul 31st, 2008, 02:41 PM
#1
Thread Starter
Frenzied Member
threading
Hi,
This is the code that I have. This code is called by a background worker.
Code:
private static void RefreshProperties(System.ComponentModel.BackgroundWorker worker, DoWorkEventArgs e)
{
using (MsWord word = new MsWord())
{
foreach (WordTemplate tmp in WordTemplates)
{
if (Worker != null && Worker.CancellationPending)
{
e.Cancel = true;
return;
}
tmp.CustomProperties = word.ReadDocumentCustomProperties(tmp);
}
}
}
The problem is that WordTemplates is being refreshed while the background worker is doing its thing and it generates an error. Is there any way I can lock WordTemplates property until the background worker is done?
Thanks,
MA
Don't anthropomorphize computers -- they hate it
-
Jul 31st, 2008, 06:53 PM
#2
Re: threading
This is exactly what is meant by objects or whatever being thread-safe. What exactly is WordTemplates? A List<> or the like. This is from the documentation for the List<T> class:
Thread Safety
Public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
A List<T> can support multiple readers concurrently, as long as the collection is not modified. Enumerating through a collection is intrinsically not a thread-safe procedure. In the rare case where an enumeration contends with one or more write accesses, the only way to ensure thread safety is to lock the collection during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.
So, having read that or its like, you have then searched for thread synchronization, correct?
http://search.msdn.microsoft.com/Def...us&refinement=
The very first match there looks like exactly the sort of thing you should be reading.
-
Aug 1st, 2008, 11:16 AM
#3
Fanatic Member
Re: threading
Code:
private static void RefreshProperties(System.ComponentModel.BackgroundWorker worker, DoWorkEventArgs e)
{
using (MsWord word = new MsWord())
{
lock (WordTemplates)
{
foreach (WordTemplate tmp in WordTemplates)
{
if (Worker != null && Worker.CancellationPending)
{
e.Cancel = true;
return;
}
tmp.CustomProperties = word.ReadDocumentCustomProperties(tmp);
}
}
}
}
However, you have to put that same lock code around anything that uses that variable, not just the code here.
Also, I should mention this is considered the "poor man's" lock. If it is heavily used, I would recommand using a Semaphore or something instead that allows a bunch of reads to go thru at the same time. It only locks while writing.
If your problem is solved, please use the Mark Thread As Resolved under Thread Tools!
Show Appreciation. Rate Posts!
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|