使用类、类的方法或类的属性都可以向线程传递参数:
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) { // ....
}