รายการซ้ำที่เป็นไปได้:
ตัวดาวน์โหลด C#: ฉันควรใช้ Threads, BackgroundWorker หรือ ThreadPool
C# เข้าถึงบางสิ่งในเธรดปัจจุบันที่สร้างในเธรดอื่นได้อย่างไร
ดังนั้นฉันจึงมีรหัสต่อไปนี้
ดาวน์โหลด.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
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();
}
}
ฉันต้องให้ Form1.Instance.log = picUrl + " is downloaded to folder " + path + ".";
ทำงานโดยไม่ต้องตั้งค่า CheckForIllegalCrossThreadCalls
เป็น false
เพราะฉันได้ยินมาว่าการกระทำต่างๆ ถือเป็นวิธีที่ไม่ดี
PS:: รหัสบางส่วนหายไป แต่ฉันคิดว่ามีข้อมูลที่เกี่ยวข้องอยู่