Results 1 to 3 of 3

Thread: Proper threading

  1. #1

    Thread Starter
    New Member
    Join Date
    Nov 2002
    Posts
    15

    Question 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.
    Nightmare

  2. #2

    Thread Starter
    New Member
    Join Date
    Nov 2002
    Posts
    15

    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...
    Nightmare

  3. #3
    Frenzied Member Memnoch1207's Avatar
    Join Date
    Feb 2002
    Location
    DUH, Guess...Hint: It's really hot!
    Posts
    1,861

    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:
    1. SyncLock
    2.    'code here
    3. 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
  •  



Click Here to Expand Forum to Full Width