Barpe2
Barpe2

Reputation: 39

How I can call async method in different class?

I have got this code:

public async Task DoRespond(AspNetWebSocketContext context)
        {
            System.Net.WebSockets.WebSocket socket = context.WebSocket;
            while (true)
            {
                ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]);
                WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, CancellationToken.None);
                if (socket.State == WebSocketState.Open)
                {
                    string userMessage = Encoding.UTF8.GetString(buffer.Array, 0, result.Count);
                    userMessage = "Message from client : " + userMessage;
                    buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(userMessage));
                    await socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
                }
                else
                {
                    break;
                }
            }

I need to call this async method in different class in bool method (it is an NUnit framework)

protected override bool Test()
{
    Websocket ws = new Websocket();
    ws.ProcessRequest(context);
    Thread.Sleep(1000);
    logger.Write("Async method ");
    var task = Task.Run(DoRespond);
}

I need to call async Task method in this bool method. How i can do that ? I aslo need call a parametre AspNetWebSocketContext context.

Upvotes: 1

Views: 2906

Answers (1)

David Culp
David Culp

Reputation: 5480

The async..await pattern is contagious and will spread thru your code base.

in order to call the async method, you need to await it in another async method

protected override async Task<bool> Test()
{
    using (Websocket ws = new Websocket()) // properly dispose of WebSocket
    {
        ws.ProcessRequest(context);
        await Task.Delay(1000); // notice the awaitable Delay replacing the blocking Sleep.
        logger.Write("Async method ");
        await DoRespond(context);
    }

    return true; // not sure where Boolean return value comes from as it wasn't in original method.
}

and, of course, whatever is calling Test() will get similar treatment.

Edit after more information in comments

The test method can be forced to wait for the async method to complete similar to this

protected override bool Test()
{
    using (Websocket ws = new Websocket()) // properly dispose of WebSocket
    {
        ws.ProcessRequest(context);
        Thread.Sleep(1000);
        logger.Write("Async method ");

        var task = DoRespond(context);
        task.Wait(); // wait for async method to complete

        // assert something?
    }

    return true; // not sure where Boolean return value comes from as it wasn't in original method.
}

However, do read up on asynchronous testing with NUnit since async test methods (like the first example) have been supported for several years.

For further reading, Async Support in NUnit

Upvotes: 1

Related Questions