C#编译器要求我让我的函数等待,但它已经是?

时间:2017-06-16 01:41:47

标签: c# async-await

这一行

internal async Task<Boolean> SendOutputReportViaInterruptTransfer
            (FileStream fileStreamDeviceData, SafeFileHandle hidHandle, Byte[] outputReportBuffer)
        {
            try
            {
                var success = false;

                    // Begin writing the Output report. 

                    Task t = fileStreamDeviceData.WriteAsync(outputReportBuffer, 0, outputReportBuffer.Length);

                    await t;

                    // Gets to here only if the write operation completed before a timeout.

                    Debug.Print("Asynchronous write completed");

                    // The operation has one of these completion states:

                    switch (t.Status)
                    {
                        case TaskStatus.RanToCompletion:
                            success = true;
                            Debug.Print("Output report written to device");
                            break;
                        case TaskStatus.Canceled:
                            Debug.Print("Task canceled");
                            break;
                        case TaskStatus.Faulted:
                            Debug.Print("Unhandled exception");
                            break;
                    }

                return success;
            }
            catch (Exception ex)
            {
                DisplayException(ModuleName, ex);
                throw;
            }
        }

给我这个错误错误

  

等待&#39;运算符只能在异步方法中使用。考虑使用&#39; async&#39;标记此方法。修饰符并将其返回类型更改为&#39;任务&#39;。 S:\ blissbox \ SOURCE_FILES \ Bliss-Box_api \ managed dx attempt \ BBAPI.cs 40

这是我的方法。

import javax.swing.JFrame;

class gui2
{
   public static void main(String args[])
   {
       frame a=new frame();
       a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       a.setSize(275*180);
       a.setVisible(true);
   }
} 

我做错了什么?

1 个答案:

答案 0 :(得分:-1)

问题是被调用的函数的位置。这意味着您调用以下代码的地方不是异步函数:

success = await _myHid.SendOutputReportViaInterruptTransfer(_deviceData, _hidHandle, outputReportBuffer);

一个解决方案可以调用此async函数,如下所示:

var task = TaskEx.RunEx(async () => 
{
   await _myHid.SendOutputReportViaInterruptTransfer(_deviceData, _hidHandle, outputReportBuffer);
});
var result = task.WaitAndUnwrapException();