我需要一種方法,給我一段時間過去的時間。我在開始過程中調用它,並在完成過程中再次調用它,並且該方法會打印經過的總時間。如何讓時間流逝的方法?
這是我的方法,但總是在00:00打印時間。爲什麼發生這種情況?
public void GetTimeElapsed(string filePath, int logSelected, bool time, IUserOptions userOptions)
{
var stopwatch = new System.Diagnostics.Stopwatch();
LogBinaryWriter BinaryWriter = new LogBinaryWriter();
string timeElapsed = "";
if(time == true)
{
stopwatch.Start();
}
if (time == false)
{
stopwatch.Stop();
TimeSpan timeSpan = stopwatch.Elapsed;
timeElapsed = (string.Format("\nFile Generated: {0}\nTime Elapsed: {1} minute(s) {2} second(s)",
BinaryWriter.CreateLogFileName(filePath, Convert.ToInt32(logSelected)),
timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds/10 + "\n"));
userOptions.DisplayUserMessage(timeElapsed);
}
}
日期時間是[不是一個好方法](http://stackoverflow.com/questions/2923283/stopwatch-vs-using-system-datetime-now-for-timing-events/2923349#2923349)的計算經過時間。 – 2011-05-05 15:59:20
@Brad Christie:感謝您的鏈接。好點子。在這種情況下,OP似乎只會將已用時間用於用戶信息,並且可能足夠精確。但是,再次感謝您指出這一點。 – DanielB 2011-05-05 16:06:08