views:

92

answers:

2

I have this code:

public partial class FrmPrincipal : Form
{
    private Image imagen;

    public FrmPrincipal()
    {
        InitializeComponent();
        ...
    }

    private void menuItem1_Click(object sender, EventArgs e)
    {
        Thread t = new Thread(RequestImage);
        t.Start();
    }

    private void RequestImage()
    {
        try
        {
            ...

            // I want to update this.token
            this.imagen = retrieveImageFromWebService();

            ...
        }
        catch (Exception ex)
        {
            ...
        }
    }
}

How can I update image? I want to save a copy of image to update a pictureBox when user needs it.

Thanks!

+2  A: 

Your code will work perfectly well is it is. However, if you want to read the value from another thread and make sure you always get the most recent value, you should either make it volatile or acquire a lock each time you read or write it.

See the memory model section of my threading article for more information.

Jon Skeet
+1  A: 

The code you have there should work fine. If you are using token in the other thread through, you'll probably want to syncronize gets and sets to avoid data corruption:

private string token {
  [MethodImpl(MethodImplOptions.Synchronized)] get;
  [MethodImpl(MethodImplOptions.Synchronized)] set;
}

This syncronization method is not 100% safe in all circumstances, but for your purposes it should work

Eric Petroelje
That ends up locking on "this" which is generally a bad idea. IMO it's better to lock on an explicit, private lock.
Jon Skeet
Jon makes a good point of course - I was going for the simplest solution here, but using a separate lock is the best practice
Eric Petroelje