写入串口时UWP未处理异常

时间:2018-01-27 20:40:16

标签: c# uwp serial-port windows-10 ntdll

我在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();
            }

        }
    }

我调用此函数的前两次代码工作正常。我第三次得到未处理的异常ntdll.dll中在等待dataWriter.StoreAsync()线。

我能看到的完整例外是:

  

xx.exe中0x00007FFCB3FCB2C0(ntdll.dll)的未处理异常:   0xC000000D:将无效参数传递给服务或函数。

This answer提到垃圾收集器关闭输入流,但我不明白为什么会在我的代码中发生。任何有关深入了解此问题的帮助都将受到高度赞赏!

2 个答案:

答案 0 :(得分:2)

原来我的问题的解决方案是在另一段代码中。我有一个函数读取这样的字节:

        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值,问题就会消失。

答案 1 :(得分:1)

通常,您不必将 plugins: [ ... new webpack.DefinePlugin({ 'process.env': { YOUR_API_KEY: JSON.stringify('VALUE') } }) ] 设置为null,因为GC将知道不再使用对象。

您最好像许多UWP样本一样调用dataWriter方法。

例如:SocketActivityStreamSocket

请阅读IDisposable.Dispose Method ()文档了解详情。