VansFannel
VansFannel

Reputation: 45921

c# threads and properties second part

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!

Upvotes: 1

Views: 133

Answers (2)

Eric Petroelje
Eric Petroelje

Reputation: 60498

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

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500475

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.

Upvotes: 2

Related Questions