|
-
Jan 20th, 2005, 04:58 AM
#1
Thread Starter
New Member
Proper threading
I have a question about what should and shouldn't be done cross-threads. Essentially I want to know if it is safe to change values created in one thread from another thread. Consider my following code:
Code:
public void AddCardToAnimate(Card aCard, int aNewX, int aNewY, bool aFlip)
{
aCard.SetAnimationValues(aNewX, aNewY, aFlip);
_cards.Add(aCard);
if(_cards.Count == 1)
{
AnimationDelegate ad = new AnimationDelegate(AnimateCards);
ad.BeginInvoke(null, ad);
}
}
private void AnimateCards()
{
// While there are still cards to be animated
while(_cards.Count!=0)
{
// Get the first card in the array
Card animatingCard = (Card)_cards[0];
// Ensure that the card being animated can be seen
animatingCard.Visible = true;
// Animate the card
MoveCard(animatingCard);
// Remove the card from the "to be animated" array
_cards.RemoveAt(0);
}
}
I know it might be confusing to know what's going on, but _cards was created in the main thread and many properties accessed within the MoveCard method were also created in the main thread.
Is this ok? Do I either need to encapsulate all of the properties that are being changed into one thread, or have many delegates?
The program seems to work fine this way...but I just want to know the proper way to go about it, and I'm a bit confused with the whole threading thing.
-
Jan 21st, 2005, 01:09 AM
#2
Thread Starter
New Member
Re: Proper threading
Ok, I think I am less confused now - but still confused.
I originally thought I had read that you should only access objects in the thread they were created.
Apparantly that isn't correct and by using the Monitor object I can ensure everything runs smoothly...
-
Jan 21st, 2005, 11:08 AM
#3
Frenzied Member
Re: Proper threading
The Monitor classes Enter and Exit methods place a lock on the method the thread calls, so the data doesn't get out of sych.
Another option is to use the SyncLock block (VB.NET) or lock (C#).
Example:
VB Code:
SyncLock
'code here
End SyncLock
C#
Code:
lock(this)
{
code here
}
Being educated does not make you intelligent.
Need a weekend getaway??? Come Visit
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
|