現在用一個用線程控制的進程條來說明,大致的步驟如下:
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)
{
}