TaskCompletionSource永远不会完成

时间:2018-10-25 21:48:48

标签: c# asynchronous xamarin xamarin.forms

我有一个websocket连接,我想为其获取get方法。我使用了这个example

这是数据模型的一部分:

public class Message
{        
    public string MessageType { get; set; }
}

public class SensorData : Message
{
    public float Temperature { get; set; }

    public float Humidity { get; set; }

    public float Pressure { get; set; }
}

这是websocket类:

public WebSocketConnection(string url)
{
    socket = new WebSocket(url);
}

private WebSocket socket;

public int Timeout = 10000;

public void Connect()
{
    socket.Connect();
    socket.OnMessage += Socket_OnMessage;

}

public void Disconnect()
{
    socket.Close();
    socket.OnMessage -= Socket_OnMessage;
}        

public event EventHandler<OnSensorDataEventArgs> SensorDataReveived;

private void Socket_OnMessage(object sender, MessageEventArgs e)
{
    var msg = JsonConvert.DeserializeObject<Message>(e.Data);

    switch (msg.MessageType)
    {
        case "other message types":
            {
                ...                       
            }
        case "SensorData":
            {
                SensorDataReveived?.Invoke(this, new OnSensorDataEventArgs(JsonConvert.DeserializeObject<SensorData>(e.Data)));
                break;
            }
    }
}

public Task<SensorData> GetSensorData()
{
        var msg = JsonConvert.SerializeObject(new Message() { MessageType = "RequestSensorData" });

    var tcs = new TaskCompletionSource<SensorData>();

    SensorDataReveived += (sender, e) => {
        tcs.SetResult(e.SensorData);
    };

    socket.Send(msg);

    return tcs.Task;
}

问题是GetSensorData方法。调用socket.Send(msg)时,Websocket服务器会应答并触发事件,但是在SetResult调用之后,什么也没有发生。我已经尝试了TaskCreationOptions.RunContinuationsAs,并将SetResult包装在Task.Run中,但这没有帮助。

private async void BtnShowSensorData_Clicked(object sender, EventArgs e)
{
    var sensorData = await connection.GetSensorData(); //Connection is an instance of WebSocketConnection
    labelTemperature.Text = "  Temperature: " + sensorData.Temperature.ToString();
    labelHumidity.Text = "  Humidity: " + sensorData.Humidity.ToString();
    labelPressure.Text = "  Pressure: " + sensorData.Pressure.ToString();
} 

0 个答案:

没有答案