现在用一个用线程控制的进程条来说明,大致的步骤如下:
1.创建Invoke函数,大致如下:
/// <summary>
/// Delegate function be invoked by main thread
/// </summary>
private void InvokeFun()
{
if(prgBar.Value< 100)
prgBar.Value = prgBar.Value + 1;
}
2.子线程入口函数:
/// <summary>
/// Thread function interface
/// </summary>
private void ThreadFun()
{
// Create invoke method by specific function
MethodInvoker mi = new MethodInvoker(this.InvokeFun);
for(int i=0; i<100; i++)
{
this.BeginInvoke(mi);
Thread.Sleep(100);
}
}
3.创建子线程:
Thread thdProcess = new Thread(new ThreadStart(ThreadFun));
thdProcess.Start();
方法二:
加入该句:Control.CheckForIllegalCrossThreadCalls = False 取消线线程安全保护模式!
方法三:带参数
使用类、类的方法或类的属性都可以向线程传递参数:
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();
注意参数是如何传递的。
方法四:带参数
ThreadStart starter = delegate { Download(yourUrl); };
new Thread(starter).Start();
//使用线程池
WaitCallback callback = delegate (object state) { Download ((string)state); };
ThreadPool.QueueUserWorkItem (callback, yourUrl);
方法五:带参数
Thread t = new Thread (new ParameterizedThreadStart(DownloadUrl));
t.Start (myUrl);
static void DownloadUrl(object url)
{
}