我是lambda和delegates的新手,但为了简单起见,我想重写一些现有的方法。
背景:有一个客户端和一个服务器应用程序将通过套接字进行通信。 CommunicationMessage 是一个保存发送/接收值的类。
我定义了一个以Actions作为参数的方法。
const options = {
nodes: { borderWidth: 2 },
edges: {length: 300, smooth: false },
physics: {
enabled: false
},
layout:{
improvedLayout: true,
hierarchical: {
levelSeparation:200,
nodeSpacing: 200,
treeSpacing:200,
}
},
interaction: { hover: true }
}
const network = new vis.Network(container, visData, options);
setTimeout(()=>{
network.setOptions({
layout:{
hierarchical: false
},
});
},1000);
此方法将如下调用:
public void SendAndReceive(CommunicationMessage query, Action<CommunicationMessage> OnReceivedResponse, Action<int> OnReceivedError, Action OnFailedSending) { ... }
正如您所看到的,我希望将该方法保留在该Lambda委托中。有没有办法实现这个目标?
感谢您的帮助!
答案 0 :(得分:0)
您可以定义另一个返回Task<CommunicationMessage>
以获取响应的方法(这类似于核心方法),然后根据该核心方法定义另一个返回Task<BaseUser>
。所有这些都可以使用TaskCompletionSource
完成,如下所示:
public Task<CommunicationMessage> SendAsync(CommunicationMessage query, Action<int> OnReceivedError, Action OnFailedSending) {
var tcs = new TaskCompletionSource<CommunicationMessage>();
SendAndReceiveAsync(query, cm => tcs.TrySetResult(cm), OnReceivedError, OnFailedSending);
return tcs.Task;
}
//for BaseUser result
public static async Task<BaseUser> LoginUserAsync(string email, string password)
{
// Create the query which will be sent to the Server
var query = MessageContentGenerator.GenerateLoginQuery(email, password).Result;
var result = await SendAsync(query, (errorCode) => {}, () => {});
return BaseUserController.Parse(result);
}
你可以找到更多关于TaskCompletionSource
的信息,以便将传统的异步方法(带回调)变成可以等待的等待方法。它甚至可以处理错误并引发异常,以便您可以无缝地使用try-catch
(无需使用错误回调)。