有没有办法在侦听器写入文件时等待。现在有一半的数据被切断了。我认为它因为TextWriterTraceListener在应用程序关闭之前设法将数据写入文件。
static void Main(string[] args)
{
Stopwatch stopwatch = new Stopwatch();
// Begin timing
stopwatch.Start();
try
{
Trace.Listeners.Add(new ConsoleTraceListener(false));
Trace.WriteLine(" ");
Trace.WriteLine(DateTime.Now);
Trace.WriteLine("Starting application...");
Trace.WriteLine("-----------------------------------------------------------");
Trace.WriteLine("Elapsed ms | Task information");
Trace.WriteLine("-----------------------------------------------------------");
Console.ForegroundColor = ConsoleColor.Green;
foreach (int i in Enumerable.Range(1, 3))
{
Trace.WriteLine("Keypair nr: " + i);
Trace.WriteLine(stopwatch.ElapsedMilliseconds + "ms | Starting to generate bytes for wrapping key..");
byte[] keyBytes = generateKeyBytes();
Trace.WriteLine(stopwatch.ElapsedMilliseconds + "ms | ..generation finished.");
Trace.WriteLine(stopwatch.ElapsedMilliseconds + "ms | Executing java to generate private and public keys..");
string keysString = runJava(keyBytes);
Trace.WriteLine(stopwatch.ElapsedMilliseconds + "ms | ..generation finished.");
string[] keys = keysString.Split(',');
byte[] pubKey = Convert.FromBase64String(keys[0]);
byte[] wrappedKey = Convert.FromBase64String(keys[1]);
Trace.WriteLine(stopwatch.ElapsedMilliseconds + "ms | Decrypting the private key..");
byte[] privKey = Decrypt(wrappedKey, keyBytes);
Trace.WriteLine(stopwatch.ElapsedMilliseconds + "ms | ..decryption finished.");
Trace.WriteLine("Public Key:\n\r" + BitConverter.ToString(pubKey));
Trace.WriteLine("Private Key:\n\r" + BitConverter.ToString(privKey));
}
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Trace.WriteLine("From: " + ex.Source + ".\nDetail: "+ ex.Message);
}
finally
{
Trace.WriteLine("Total Elapsed time: " + stopwatch.Elapsed);
stopwatch.Stop();
Console.WriteLine("Any key to exit..");
Console.ReadKey();
}
}
添加了我的代码。 在配置文件中我有:
<system.diagnostics>
<trace autoflush="false" indentsize="4">
<listeners>
<add name="myListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="output.log" />
<remove name="Default" />
</listeners>
</trace>
</system.diagnostics>
打印出来的最后一个字节数组被切掉,来自finnaly块的行也会从output.log中丢失,但它们仍会显示在控制台上。
答案 0 :(得分:4)
Trace和Debug类具有Flush,Close和AutoFlush成员。您需要至少使用其中一个。 ConsoleListener在没有它们的情况下工作是偶然的。