我有以下c#代码,正在向其中发送一系列请求和响应
#[derive(Deserialize)]
异步函数发送和接收,具有以下代码。
public static async Task AuthenticateQvpx2()
{
var handshake = new Handshake();
foreach (var request in handshake.AutheticateStrings)
{
var buffer = _encoder.GetBytes(request);
await Task.WhenAll(Receive(_webSocket), Send(_webSocket, buffer));
}
}
我希望将请求和响应收集到一个数组/任何形式的数据类型中。
我遇到麻烦了,因为我不确定下一步该怎么做?
答案 0 :(得分:1)
我希望收集请求和回复
收集请求有点奇怪,因为该数据已经存在(在buffer
变量中)。
假设您只需要响应,则可以使用await
:
public static async Task AuthenticateQvpx2()
{
var handshake = new Handshake();
foreach (var request in handshake.AutheticateStrings)
{
var buffer = _encoder.GetBytes(request);
var receiveTask = Receive(_webSocket);
await Task.WhenAll(receiveTask, Send(_webSocket, buffer));
var response = await receiveTask;
}
}
答案 1 :(得分:0)
不确定基于您的摘要,Send
和Receive
返回哪种类型的任务,但是通常在使用Task.WhenAll
通过LINQ使用
var handshake = new Handshake();
List<Task<WebsocketReceiveResult>> tasks = newList<Task<WebsocketReceiveResult>>();
foreach (var request in handshake.AutheticateStrings)
{
var buffer = _encoder.GetBytes(request);
tasks.Add(webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None));
}
await Task.WhenAll(tasks);
var resultArray = tasks.Select(t => t.Result).ToArray();
之后,您可以从多个任务中获得结果:>
let data = [
{
"id": "denuzi",
"sub":
[
{"id": "s4p58o"},
{"id": "xzbqi"},
],
},
{
"id": "4rcodm",
"sub": [],
}
]
function remove(data, removeId){
return data
.filter(({id}) => id!==removeId) // removes parent object if its id matches removeId
.map(({id, sub}) => ({id, sub: sub.filter(({id}) => id!==removeId)})) // replaces sub array with new sub array with subobject missing
}
console.log(remove(data, "s4p58o"));
console.log(remove(data, "denuzi"))
答案 2 :(得分:0)
尝试类似
ConcurrentDictionary<Guid, (System.Byte[], WebSocketReceiveResult)> x = new ConcurrentDictionary<Guid, (byte[], WebSocketReceiveResult)>();
在foreach中生成GUID,并将其传递给您的方法:
foreach (var request in handshake.AutheticateStrings)
{
var buffer = _encoder.GetBytes(request);
var guid = Guid.NewGuid();
await Task.WhenAll(Receive(_webSocket, guid), Send(_webSocket, buffer, guid));
}
然后,您可以自然地从Receive和Send方法中使用字典。
void Send(WebSocket webSocket, byte[] buffer, Guid guid)
{
x.GetOrAdd(guid, new ValueTuple<System.Byte[], WebSocketReceiveResult>(buffer, null));
await webSocket.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None)
}
void Receive(WebSocket webSocket, Guid guid)
{
var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
x[guid].Item2 = result;
}