c# - Slight lag spawning new thread causes race condition -
I have some initial code that runs in a new thread, and takes 4-5 seconds to run: / P>
Start Public Virtual Zero () {Adapter. Start (this); New thread (rep () () () (InitLock.WriteLock ()) / / - InitLock is a reader author. = New modeler proxy (this), modeler. Load snapshot (); pars = new pars (); Load templates (); }}) Start (); }
I also have several methods that use the objects started in that thread, although they use the same ReaderWriterLockSlim
object so that they Can not block if necessary objects have not been started yet:
public virtual parser parser {get (using InLock.ReadLock ()) {return parser; }}}
Now, if I run this code:
context.Initialize (); // Start the call method above // Some other stuff that takes a short time reference. Pars Purse ("blah blah");
Then, everything works, however, if I run this code:
context.Initialize () ; // calls start the reference in the initial way. Parser Percy ("blah blah"); // Call the parse immediately
Then I get an empty reference exception on parser
. In other words, my initialization code has not yet been run, and WriteLock
has not been installed, so it will not block the thread.
I have discovered the fact that there is one such minor non-blocking gap at the time of creating a new thread NAT. If I add this code:
}}). Start (); Thread.Sleep (500); / /
provides time to start and get thread to start and sleeps for half a second, everything works great.
My question: I think that sleep
is a call, and there is a possibility to behave differently on different systems. Is there a better design to wait until the new thread gets locked before leaving the main thread? I can get the lock in the first thread and remove it in another thread, but it looks like more hamy!
Comments
Post a Comment