我需要知道这个线程何时完成了它正在做的事情。在背景上也有一个活跃的计时器。
注意:"扫描仪"是一个递归函数
// button click
//timer
timer.Enabled = true;
//thread
System.Threading.ThreadStart start = delegate { scanner(@"c:\", "*.txt;*.html;"); };
System.Threading.Thread thread = new System.Threading.Thread(start);
thread.Start();
-------------
private static long Counter = 0;
private static string scanstatus = string.Empty;
private static void scanner(string folder, string patterns)
{
// Get the patterns.
string[] pattern_array = patterns.Split(';');
foreach (string pattern in pattern_array)
{
try
{
foreach (string fileName in System.IO.Directory.GetFiles(folder, pattern))
{
//trim path
scanstatus = (fileName.Length > 50) ? "../" + fileName.Substring(fileName.Length - 49, 49) : fileName;
// delay
//System.Threading.Thread.Sleep(5);
Counter++;
}
}
catch (System.Exception E)
{
Console.WriteLine(E.Message);
}
}
try
{
foreach (string directory in System.IO.Directory.GetDirectories(folder))
scanner(directory, patterns);
}
catch (System.Exception E)
{
Console.WriteLine(E.Message);
}
}
答案 0 :(得分:0)
答案 1 :(得分:0)
使用背景工作者,它可以让你跟踪工作状态(进度事件),已完成的事件,你可以取消它
using System;
using System.Threading;
using System.ComponentModel;
class Program
{
static BackgroundWorker _bw;
static void Main()
{
_bw = new BackgroundWorker
{
WorkerReportsProgress = true,
WorkerSupportsCancellation = true
};
_bw.DoWork += bw_DoWork;
_bw.ProgressChanged += bw_ProgressChanged;
_bw.RunWorkerCompleted += bw_RunWorkerCompleted;
_bw.RunWorkerAsync ("Hello to worker");
Console.WriteLine ("Press Enter in the next 5 seconds to cancel");
Console.ReadLine();
if (_bw.IsBusy) _bw.CancelAsync();
Console.ReadLine();
}
static void bw_DoWork (object sender, DoWorkEventArgs e)
{
for (int i = 0; i <= 100; i += 20)
{
if (_bw.CancellationPending) { e.Cancel = true; return; }
_bw.ReportProgress (i);
Thread.Sleep (1000); // Just for the demo... don't go sleeping
} // for real in pooled threads!
e.Result = 123; // This gets passed to RunWorkerCompleted
}
//here set your scanner work
static void bw_RunWorkerCompleted (object sender,
RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
Console.WriteLine ("You canceled!");
else if (e.Error != null)
Console.WriteLine ("Worker exception: " + e.Error.ToString());
else
Console.WriteLine ("Complete: " + e.Result); // from DoWork
}
static void bw_ProgressChanged (object sender,
ProgressChangedEventArgs e)
{
Console.WriteLine ("Reached " + e.ProgressPercentage + "%");
}
}
答案 2 :(得分:-1)
如果您想知道线程何时结束,您可以执行以下操作:
DateTime _startTime=DateTime.Now;
TimeSpan _elapsedTime;
.....
thread.Start();
while(thread.IsAlive)
{
Thread.Sleep(100);
}
private static void scanner(string folder, string patterns)
{
// do your work here
_elapsedTime=DateTime.Now.Subtract(_startTime);
}
但您需要更具体地了解with whatever is it doing