0

Firstly,the CAN device receives message,and calling the following method

private List<string> recordList = new List<string>();//
private List<string> recordList1 = new List<string>();//
private List<string> recordList2 = new List<string>();//

 public void FrameReceived(CANFrame frame)
 {

     if (!isRecord) return;
     if (frame != null)
     {
         string record = RecordFrame(frame, "Rx");
         recordList.Add(record);
         if (frame.Channel == 1) recordList1.Add(record);
         if (frame.Channel == 2) recordList2.Add(record);
     }
 }

 public string RecordFrame(CANFrame frame, string type)
 {
     string text1 = string.Empty;
     if (frame.type == TPCANMessageType.PCAN_MESSAGE_STANDARD)
     {
         text1 = ($"{stopwatch.ElapsedTicks * 1.0 / Stopwatch.Frequency,11:#0.000000} {frame.Channel}  {frame.Id,-15:X} {type}   d {frame.Length} {frame.ToHexString()}");
     }
     else if (frame.type == TPCANMessageType.PCAN_MESSAGE_EXTENDED)
     {
         text1 = ($"{stopwatch.ElapsedTicks * 1.0 / Stopwatch.Frequency,11:#0.000000} {frame.Channel}  " + $"{frame.Id:X}x".PadRight(15) + $" {type}   d {frame.Length} {frame.ToHexString()}");
     }
     else if (frame.type == TPCANMessageType.PCAN_MESSAGE_FD)
     {
         text1 = ($"{stopwatch.ElapsedTicks * 1.0 / Stopwatch.Frequency:#0.000000} CANFD {frame.Channel} {type} {frame.Id:X} 0 0 1 {frame.DLC:X2} {frame.Length} {frame.ToHexString()} 0 0 39b5 0 0 0 0");
     }
     
     else
     {
         if (frame.Data.Length <= 8)
         {
             text1 = ($"{stopwatch.ElapsedTicks * 1.0 / Stopwatch.Frequency,11:#0.000000} {frame.Channel}  " + (frame.Id > 0x7FF ? $"{frame.Id:X}x".PadRight(15) : $"{frame.Id,-15:X}") + $" {type}   d {frame.Length} {frame.ToHexString()}");
         }
         else
         {
             text1 = ($"{stopwatch.ElapsedTicks * 1.0 / Stopwatch.Frequency:#0.000000} CANFD {frame.Channel} {type} " + (frame.Id > 0x7FF ? $"{frame.Id:X}x" : $"{frame.Id:X}") + $" 0 0 1 {frame.DLC:X2} {frame.Length} {frame.ToHexString()} 0 0 39b5 0 0 0 0");
         }
     }
     return text1;

 }

Then,I call follwing method to store the message

 public void StartRecord(string fileName)
 {
     this.fileName = fileName;
     stopwatch.Reset();
     stopwatch.Start();

     recordList.Clear();
     recordList1.Clear();
     recordList2.Clear();
     isRecord = true;
 }
 public void StopRecord()
 {
     isRecord = false;
     WriteToFile();
     
     stopwatch.Stop();

 }
private async void WriteToFile()
{
    try
    {
        Task writeAll = WriteToFileAsync($"{fileName}\\合并CAN.asc", new List<string>(recordList));
        Task write1 = WriteToFileAsync($"{fileName}\\内CAN.asc", new List<string>(recordList1));
        Task write2 = WriteToFileAsync($"{fileName}\\外CAN.asc", new List<string>(recordList2));
        await Task.WhenAll(writeAll, write1, write2);
    }
    catch(Exception ex)
    {
        SmartFrameWork.Console.WriteLine("WriteToFile()");
        SmartFrameWork.Console.WriteLine(ex.ToString());
    }
}
async Task WriteToFileAsync(string fileName,List<string> lines)
{
    try
    {
        using (StreamWriter writer = new StreamWriter(fileName))
        {
            await writer.WriteLineAsync($"date {DateTime.Now.ToString("dd/M/yyyy HH:mm:ss.fff")}");
            await writer.WriteLineAsync("base hex  timestamps absolute");
            await writer.WriteLineAsync("no internal events logged");
            await writer.WriteLineAsync($"//Version 5.6");
            foreach (var line in lines)
            {
                if (writer == null)
                    SmartFrameWork.Console.WriteLine("writer为空");
                if (line == null)
                    SmartFrameWork.Console.WriteLine("写入该行的内容为空");
                await writer.WriteLineAsync(line);

            }
            await writer.FlushAsync(); 
        }
    }
    catch(Exception ex)
    {
        SmartFrameWork.Console.WriteLine("WriteToFileAsync(string fileName,List<string> lines)");
        SmartFrameWork.Console.WriteLine(ex.ToString());
    }
   
}

the exception infomation:

System.NullReferenceException:未将对象引I用设置到对象的实例。 在 System.IO.StreamWriter.<WriteAsynclnternal>d_55.MoveNext() ---引发异常的上一位置中堆栈跟踪的末尾· 在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 在 System.Runtime.CompilerServices.TaskAwaiter.GetResulto 在 CANBusDriver.FileFrameFilter.<WriteToFileAsync>d_35.MoveNext() 位置 D:\Projects\HIL\HIL_ fanqingyu\V5.6Beta\HIL\CANdriver\FileFrameFilter.cs:行号157 --引发异常的上一位置中堆栈跟踪的末尾-- 在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 在 System.Runtime.CompilerServices.TaskAwaiter.GetResult() 在 CANBusDriver.FileFrameFilter.<WriteToFile>d_34.MoveNext() 位置 D:\Projects\HIL\HIL_ fanqingyu\V5.6Beta\HIL\CANdriver\FileFrameFilter.cs:行号 145 --引发异常的上一位置中堆栈跟踪的末尾-- 在 System.Runtime.CompilerServices.AsyncMethodBuilderCore.<>c.≤ThrowAsync>b6_1(0bject state) 在 System.Threading.QueueUserWorkltemCallback.WaitCallback_ Context(Object state) 在 System.Threading.ExecutionContext.Runlnternal(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) 在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback callback, Object state, Boolean preserveSyncCtx) 在 System.Threading.QueueUserWorkitemCallback.System.Threading.IThreadPoolWorkltem.ExecuteWorkltem() 在 System.Threading.ThreadPoolWorkQueue.Dispatch() 在 System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()

the line 157 means "await writer.WriteLineAsync(line);" the line 145 means "await Task.WhenAll(writeAll, write1, write2);" This exception is an occasional occurrence, not a definite occurrence,according to the exception information,there is a NullReferenceException,and the exception rised by the statement "await writer.WriteLineAsync(line);" .I am sure the "line" is not null,because before i add it to the List,its initial value is string.Empty,but the "writer" has worked.the "ChatGPT" tells me it happend inside the method of"await writer.WriteLineAsync(line);",i can not understand `

11
  • This question is similar to: Task.WhenAll not throwing exception as expected. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Sep 4, 2024 at 7:29
  • Which of the two catch clauses are you referring to? Did you already use the Debugger to find the place where the NullReferenceException occurs? Commented Sep 4, 2024 at 8:08
  • the line 157 means "await writer.WriteLineAsync(line);" the line 145 means "await Task.WhenAll(writeAll, write1, write2);" This exception is an occasional occurrence, not a definite occurrence,according to the exception information,there is a NullReferenceException,and the exception rised by the statement "await writer.WriteLineAsync(line);" .I am sure the "line" is not null,because before i add it to the List<string>,its initial value is string.Empty,but the "writer" has worked.the "ChatGPT" tells me it happend inside the method of"await writer.WriteLineAsync(line);",i can not understand Commented Sep 4, 2024 at 8:33
  • 1
    Can you please edit your question to add this additional information? Commented Sep 4, 2024 at 8:55
  • 1
    async void WriteToFile() - why is this not async Task? As it is now, this method cannot be awaited. How do you call it? Commented Sep 4, 2024 at 9:06

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.