0

Possible Duplicate:
C# Downloader: should I use Threads, BackgroundWorker or ThreadPool?
C# , how reach something in current thread that created in other thread?

So I have following code

Downloader.cs

class Downloader
{  
    private WebClient wc = new WebClient();
    public void saveImages(string picUrl, string path)
    {
                this.wc.DownloadFile(picUrl, path + p);
                Form1.Instance.log = picUrl + " is downloaded to folder " + path + ".";
    }
}

Form1.cs / Windows Form

public partial class Form1 : Form
{
    static Form1 instance;
    public static Form1 Instance { get { return instance; } }

    protected override void OnShown(EventArgs e)
    {
        base.OnShown(e);
        instance = this;
    }

    protected override void OnClosed(EventArgs e)
    {
        base.OnClosed(e);
        instance = null;
    }
    public string log
    {
        set { logbox.AppendText(value); } // Logbox is Rich Text Box
    }
    private void ThreadJob()
    {
        Downloader r = new Downloader();
        r.saveImages("http://c.org/car.jpg","c:/temp/");
    }
    private void download_Click(object sender, EventArgs e)
    {
        ThreadStart job = new ThreadStart(ThreadJob);
        Thread thread = new Thread(job);
        CheckForIllegalCrossThreadCalls = false;
        thread.Start();
    }
}

I need to get Form1.Instance.log = picUrl + " is downloaded to folder " + path + "."; working without CheckForIllegalCrossThreadCalls set to false because I've heard it's bad way to do things.

PS:: Some of the code is missing but I think the relevant information is there

Community
  • 1
  • 1
Crazywako
  • 362
  • 2
  • 6
  • 15

2 Answers2

1

Rather than having saveImages be a void method and modifying the form, saveImages should return the string value that it computes and allow the form to modify itself:

public string saveImages(string picUrl, string path)
{
            this.wc.DownloadFile(picUrl, path + p);
            return picUrl + " is downloaded to folder " + path + ".";
}

Now what you're really looking for is a way of performing a long running task in a background thread and updating the UI with the result. The BackgroundWorker class is specifically designed for that purpose, and is much easier to use in a winform application than directly dealing with threads.

You just need to create a BackgroundWorker, set the work that it needs to do in the DoWork event, and then update the UI in the RunWorkerCompleted event.

In this case, the DoWork just needs to call saveImages and then set the Result to the return value and then the completed event can add the Result to the rich text box. The BackgroundWorker will ensure that the completed event will be run by the UI thread.

Servy
  • 202,030
  • 26
  • 332
  • 449
1

See documentation on BackgroundWorker or Control.Invoke. Remember google is your friend.

Richard Schneider
  • 34,944
  • 9
  • 57
  • 73