有趣的多线程编程(2)——线程中的参数传递

使用类、类的方法或类的属性都可以向线程传递参数:
public
class UrlDownloader { string url; public UrlDownloader (string url) { this.url = url; } public void Download() {
WebClient wc = new WebClient();
Console.WriteLine("Downloading " + url); byte[] buffer = wc.DownloadData (url); string download = Encoding.ASCII.GetString(buffer); Console.WriteLine(download); Console.WriteLine("Download successful.");
//这里你可以将download进行保存等处理...... } } [... 在另一个类中使用它们...] UrlDownloader downloader = new UrlDownloader (yourUrl); new Thread (new ThreadStart (downloader.Download)).Start();
注意参数是如何传递的。
在.NET 2.0中还可以这样:
(CODE-BESIDE)
方式一:
ThreadStart starter = delegate { Download(yourUrl); });
new Thread(starter).Start();
//使用线程池
WaitCallback callback = delegate (object state) { Download ((string)state); };
ThreadPool.QueueUserWorkItem (callback, yourUrl);
 
  
方式二(使用ParameterizedThreadStart):
Thread t = new Thread (new ParameterizedThreadStart(DownloadUrl));
t.Start (myUrl);

static void DownloadUrl(object url)
{
    // ....
}

你可能感兴趣的:(C#类)