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
Rather than having
saveImagesbe avoidmethod and modifying the form,saveImagesshould return the string value that it computes and allow the form to modify itself: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
BackgroundWorkerclass 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 theDoWorkevent, and then update the UI in theRunWorkerCompletedevent.In this case, the
DoWorkjust needs to callsaveImagesand then set theResultto the return value and then the completed event can add theResultto the rich text box. TheBackgroundWorkerwill ensure that the completed event will be run by the UI thread.