【发布时间】:2015-02-13 15:56:27
【问题描述】:
我有一个与 SignalR Hub(服务器)通信的 .Net Windows 服务(客户端)。大多数客户端方法都需要时间来完成。当收到来自服务器的调用时,我如何(或者我需要)包装目标方法/hub.On以避免警告:
“由于没有等待此调用,因此在调用完成之前继续执行当前方法。考虑将 await 运算符应用于调用结果”
在客户端,这是一个启动/设置代码示例:
IHubProxy _hub
string hubUrl = @"http://localhost/";
var connection = new HubConnection(hubUrl, hubParams);
_hub = connection.CreateHubProxy("MyHub");
await connection.Start();
_hub.On<Message>("SendMessageToClient", i => OnMessageFromServer(i.Id, i.Message));
_hub.On<Command>("SendCommandToClient", i => OnCommandFromServer(i.Id, i.Command));
同样在客户端,这是一个方法示例:
public static async Task<bool> OnMessageFromServer(string Id, string message)
{
try
{
var result = await processMessage(message); //long running task
}
catch (Exception ex)
{
throw new Exception("There was an error processing the message: ", ex);
}
return result;
}
public static async Task<bool> OnCommandFromServer(string Id, string command)
{
try
{
var result = await processCommand(command); //long running task
}
catch (Exception ex)
{
throw new Exception("There was an error processing the message: ", ex);
}
return result;
}
最终,我认为 _hub.On 正在注册回调,而不是来自服务器的实际执行(调用)。我想我需要进入实际执行的中间,等待 On[X]FromServer 的结果并返回结果。
******************更新的示例,带有更正的代码*********************
IHubProxy _hub
string hubUrl = @"http://localhost/";
var connection = new HubConnection(hubUrl, hubParams);
_hub = connection.CreateHubProxy("MyHub");
await connection.Start();
//original
//_hub.On<Message>("SendMessageToClient", i => OnMessageFromServer(i.Id, i.Message));
//_hub.On<Command>("SendCommandToClient", i => OnCommandFromServer(i.Id, i.Command));
//new async
_hub.On<Message>("SendMessageToClient",
async (i) => await OnMessageFromServer(i.Id, i.Message));
_hub.On<Message>("SendCommandToClient",
async (i) => await OnCommandFromServer(i.Id, i.Message));
//expanding to multiple parameters
_hub.On<Message, List<Message>, bool, int>("SendComplexParamsToClient",
async (p1, p2, p3, p4) =>
await OnComplexParamsFromServer(p1.Id, p1.Message, p2, p3, p4));
然后目标方法签名将类似于
public static async Task<bool> OnComplexParamsFromServer(string id, string message,
List<Message> incommingMessages, bool eatMessages, int repeat)
{
try
{
var result = await processCommand(message); //long running task
if (result)
{
// eat up your incoming parameters
}
}
catch (Exception ex)
{
throw new Exception("There was an error processing the message: ", ex);
}
return result;
}
感谢@AgentFire 的快速响应!!!
【问题讨论】:
-
建议不要使用
.Wait();,而是使用await connection.Start()。 -
感谢您的提示...我已更新代码以反映未来的读者。
标签: c# .net async-await signalr.client