Forum Xamarin.Forms

TaskCompletitionSource in Xamarin.Forms never completes

Hello,

I'm trying to implement a websocket client in my xamarin.forms application. I'm using the websocketsharp-netstandard from nuget and its working fine, the event gets triggered when the server sends something to the client.
But I want to change the event based asynchronous pattern to async/await pattern.
So a method should send the request, wait for the event to be triggered and then return the result.
Here is the code from the FormsApp I made to test, its more minimalistic and overseeable than the extract from my Xamarin.Forms app, but it's the same as in my Xamarin.Forms app:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            socket = new WebSocket("wss://echo.websocket.org");   //This is a test websocket server which just sends back what it receives 
            socket.Connect();            
        }        
        WebSocket socket;        

        private async void button1_Click(object sender, EventArgs e)
        {        
            textBox1.Text = await GetWsMsg();
        }

        public Task<string> GetWsMsg()
        {
            TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();

            socket.OnMessage += (s,e) => {

                tcs.SetResult(e.Data);                 //Here it gets stuck in Xamarin.Forms
            };
            socket.Send("Hello Websocket");
            return tcs.Task;
        }
    }    

This works well in the .NET forms app, but in Xamarin.Forms the "GetWsMsg" method never returns.
Is this a known problem in Xamarin.Forms or Is there a alternative or a workaround?
Any help highly appreciated!

Tagged:

Answers

  • ObrockiObrocki Member ✭✭

    Doesn't the GetWsMsg method have to be async/await as well?

  • ChingonSheepChingonSheep Member ✭✭
    edited October 2018

    @Obrocki I don't think so, because the return type has to be a the Task object which is contained by the TaskCompletitionSource. If I would declare it as async, I had to return the T type of the Task and not the Task itself, that would make no sense because there would be nothing to await.
    But the call of GetWsMsg can be with await.

    Edit: This is the documentation I got that from: docs.microsoft.com/en-us/dotnet/standard/asynchronous-programming-patterns/interop-with-other-asynchronous-patterns-and-types#tasks-and-the-event-based-asynchronous-pattern-eap

Sign In or Register to comment.