簡體   English   中英

寫入串行時的UWP未處理異常

[英]UWP Unhandled Exception when writing to serial

我在UWP中寫入串行設備時遇到問題。 我寫端口的任務如下:

    public async Task WriteAsync(byte[] stream)
    {
        if (stream.Length > 0 && serialDevice != null)
        {
            await writeSemaphore.WaitAsync();
            try
            {
                DataWriter dataWriter = new DataWriter(serialDevice.OutputStream);

                dataWriter.WriteBytes(stream);

                await dataWriter.StoreAsync();
                dataWriter.DetachStream();
                dataWriter = null;                    
            }
            finally
            {
                writeSemaphore.Release();
            }

        }
    }

我調用此函數的前兩次,代碼運行良好。 我第三次在await dataWriter.StoreAsync()行的ntdll.dll中得到未處理的異常。

我可以看到的完整異常是:

xx.exe中0x00007FFCB3FCB2C0(ntdll.dll)的未處理異常:0xC000000D:無效的參數傳遞給服務或函數。

這個答案提到了垃圾收集器關閉了輸入流,但是我不明白為什么它會在我的代碼中發生。 對於深入了解此問題的任何幫助,我們將不勝感激!

事實證明,解決我的問題的方法是在另一段代碼中。 我有一個讀取字節的函數,如下所示:

        private async Task ReadAsync(CancellationToken cancellationToken)
    {
        Task<UInt32> loadAsyncTask;

        uint ReadBufferLength = 1024;

        // If task cancellation was requested, comply
        cancellationToken.ThrowIfCancellationRequested();

        // Set InputStreamOptions to complete the asynchronous read operation when one or more bytes is available
        dataReader.InputStreamOptions = InputStreamOptions.Partial;

        using (var childCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
        {
            // Create a task object to wait for data on the serialPort.InputStream
            loadAsyncTask = dataReader.LoadAsync(ReadBufferLength).AsTask(childCancellationTokenSource.Token);

            // Launch the task and wait
            UInt32 bytesRead = await loadAsyncTask;
            if (bytesRead > 0)
            {
                byte[] vals = new byte[3]; //TODO:adjust size
                dataReader.ReadBytes(vals);
                //status.Text = "bytes read successfully!";
            }
        }
    }

具體來說,問題出在以下兩行:

byte[] vals = new byte[3]; //TODO:adjust size
dataReader.ReadBytes(vals);

一旦將vals數組的大小設置為bytesRead值,問題就消失了。

通常,您不必將dataWriter設置為null,因為GC將知道不再使用對象。

您最好像許多UWP示例一樣調用dataWriter.Dispose()方法。

例如: SocketActivityStreamSocket

請閱讀IDisposable.Dispose方法()文檔以獲取更多詳細信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM