我有这段代码:
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;
}
}
我需要在bool方法的不同类中调用这个异步方法(它是一个NUnit框架)
protected override bool Test()
{
Websocket ws = new Websocket();
ws.ProcessRequest(context);
Thread.Sleep(1000);
logger.Write("Async method ");
var task = Task.Run(DoRespond);
}
我需要在这个bool方法中调用async Task方法。我怎么能这样做?我还需要调用一个参数AspNetWebSocketContext上下文。
答案 0 :(得分:1)
async..await
模式具有传染性,并将通过您的代码库传播。
要调用async
方法,您需要await
另一个async
方法
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.
}
当然,无论调用Test()
,都会得到类似的处理。
在评论中提供更多信息后进行修改
可以强制测试方法等待async
方法完成,类似于
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.
}
但是,请阅读使用NUnit的异步测试,因为async
测试方法(如第一个示例)已支持多年。
进一步阅读,Async Support in NUnit