簡體   English   中英

C#async並在winforms中等待串行通信

[英]C# async and await in winforms for serial communication

我在這里編寫了一個片段,用於異步完成串行數據傳輸。 VS2015拋出一條消息,表明該方法將同步運行並缺少等待。 請告訴我哪里出錯了。

    private bool SendRecieveSerialData(string port, byte Cmd, string fileName)
    {
        // bool write_status = ReadWriteSerialData(port, Cmd, fileName);
        bool write_status = SendandReceiveAsync(port,Cmd,fileName).Result;
        if (write_status)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    //private bool ReadWriteSerialData(string port,byte Command, string fileName)

    public bool ReadWriteSerialData(string port,byte Command, string fileName)
    {
        bool comFlag = false;

        if (String.IsNullOrEmpty(port))
        {

            log.WriteErrorLog("Null Port");
            comFlag = false;
            return comFlag;
        }
        else
        {
          //  SerialPortFixer.Execute(port);
            serialPort = new SerialPort(port);

           for (int count = 0; count < BluetoothGlobals.retry_count; count++)
            {


                byte[] text = File.ReadAllBytes(fileName);


                try
                {
                    if (!serialPort.IsOpen)
                    {
                        ConnectedFlag = true;
                        if (fileName != null)
                        {
                            for (int counter = 0; counter < text.Length; counter += 256)
                            {
                                int tempsize = text.Length - counter;

                                if(tempsize > 256)
                                {
                                    tempsize = 256;
                                }

                                Array.Clear(DataFrame, 0, DataFrame.Length);
                                DataFrame[0] = (byte)(MessageFormat.START_FRAME); //Start frame
                                DataFrame[1] = (byte)(tempsize); // Frame Size to be dynamic
                                DataFrame[2] = (byte)(Command & 0xFFu); // LSB
                                DataFrame[3] = (byte)((Command >> 8) & 0xFFu); // MSB
                                Array.Copy(text, counter, DataFrame, 4, tempsize);
                                DataFrame[tempsize + 4] = (byte)(ComputeCheckSum(DataFrame) & 0xFFu);
                                DataFrame[tempsize + 5] = (byte)(((ComputeCheckSum(DataFrame) >> 8) & 0xFFu)); // MSB
                                DataFrame[tempsize + 6] = (byte)(MessageFormat.END_FRAME);


                            }
                        }
                        else
                        {                                    
                            DataFrame[0] = (byte)(MessageFormat.START_FRAME); //Start frame
                            DataFrame[1] = (byte)(MessageFormat.PING_SIZE); // Frame Size to be dynamic
                            DataFrame[2] = (byte)(Command & 0xFFu); // LSB
                            DataFrame[3] = (byte)((Command >> 8) & 0xFFu); // MSB
                            DataFrame[4] = 0; 
                            DataFrame[5] = (byte)(ComputeCheckSum(DataFrame) & 0xFFu);
                            DataFrame[6] = (byte)(((ComputeCheckSum(DataFrame) >> 8) & 0xFFu)); // MSB
                            DataFrame[7] = (byte)(MessageFormat.END_FRAME);
                        }

                        serialPort.Open();
                        serialPort.BaudRate = 115200;
                        serialPort.Parity = Parity.None;
                        serialPort.StopBits = StopBits.One;
                        serialPort.Handshake = Handshake.None;
                        serialPort.DataBits = 8;
                        serialPort.Write(DataFrame, 0, DataFrame.Length);
                        serialPort.DataReceived += new SerialDataReceivedEventHandler(Current_port_DataReceived);
                        comFlag = true;

                         if (comFlag)
                        {

                            break;
                        }

                    }
                }
                catch (Exception e)
                {
                    log.WriteErrorLog(e.Message);
                    continue;
                }
            }

        }

        return comFlag;
    }

    public async Task<bool> SendandReceiveAsync(string portnum,byte cmd, string file)
    {

        bool task_state = await Task.Factory.StartNew(() => ReadWriteSerialData(portnum, cmd, file));

        if (task_state)
            return true;
        else
            return false;
    }

methoddeclaration中的關鍵字async不會使方法異步運行。 只有在使用async關鍵字聲明的方法內使用await調用的方法調用才會異步執行。

例如:

public async Task RunPartsAsync()
{
    using(var someStream = new SomeStream(someSource))
    {
        await someStream.ReadAsync(); //this will be executed asynchronously

        someStream.ReadAsync(); //this will be executed asynchronously but not awaited
                                // => Console.WriteLine might be called/finish before ReadAsync finished

        Console.WriteLine("asdf"); //this will NOT be executed asyncronously
    }
}

您可以嘗試以下方法:

  1. 讓你方法同步

     public bool ReadWriteSerialData(string port, byte Command, string fileName) { var comFlag = false; // ... your cdode here..... return comFlag; } 
  2. 將其作為單獨的任務調用

     public async Task<bool> SendandReceiveAsync(string portnum, byte cmd, string file) { bool task_state = await Task.Factory.StartNew(()=>ReadWriteSerialData(portnum, cmd, file)); if (task_state) return true; else return false; } 

這樣做: http//blog.stephencleary.com/2012/02/async-and-await.html

public async Task NewStuffAsync()
{
  // Use await and have fun with the new stuff.
  await ...
}

public Task MyOldTaskParallelLibraryCode()
{
  // Note that this is not an async method, so we can't use await in here.
  ...
}

public async Task ComposeAsync()
{
  // We can await Tasks, regardless of where they come from.
  await NewStuffAsync();
  await MyOldTaskParallelLibraryCode();
}

如果您從事件中調用ComposeAsync

public async void ButtonClick(object sender, System.EventArgs e)  {
  await ComposeAsync; //or
  await Task.Run(() => ComposeNonAsync());
}

暫無
暫無

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

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