在我的Xamarin应用程序聊天中添加实时功能会引发System.InvalidOperationException



我创建了一个Xamarin应用程序,该应用程序带有聊天和API来存储数据,移动应用程序每3分钟向API请求一次聊天消息。

我决定按照评论中的建议使用SignalR:

-将其添加到我的CongifureService中,如图所示:

public void ConfigureServices(IServiceCollection services)
{           
services.AddDbContext<HostelContext>(opt =>
opt.UseSqlServer(Configuration.GetConnectionString("HostelContext")));
services.AddCors();
services.AddControllers();
services.AddAuthentication("BasicAuthentication")
.AddScheme<AuthenticationSchemeOptions, BasicAuthenticationHandler>("BasicAuthentication", null);
services.AddScoped<IUsersService, UsersService>();
services.AddScoped<IConversationsService, ConversationsService>();
services.AddScoped<IMessagesService, MessagesService>();
// Register the Swagger generator, defining 1 or more Swagger documents
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "HostelApi", Version = "v1" });             
});
services.AddSignalR();
}

-添加了要配置的端点,如图所示:

app.UseEndpoints(endpoints =>
{                
endpoints.MapControllers();
endpoints.MapHub<ChatHub>("/chatHub");
});

-在名为Hub 的新文件夹中将Class添加到我的api项目中

-这是集线器类:

//[Authorize]    
public class ChatHub : Hub
{                
public async Task SendMessage(Message message)
{
//await Clients.All.SendAsync("ReceiveMessage", message);
await Clients.All.SendAsync("ReceiveMessage" + message.ConversationId, message);
//await Clients.Users(destinationUserIdList).SendAsync("ReceiveMessage" + message.ConversationId, message);
}
}

在我的Xamarin应用程序中:

-增加集线器服务:

-这是集线器服务类别:

class HubService : IHubService
{
public HubConnection HubConnection { get; }
public HubService()
{
HubConnection = new HubConnectionBuilder()
.WithUrl($"https://10.0.2.2:5001/chatHub")
.Build();
}
public async Task Connect()
{
await HubConnection.StartAsync().ConfigureAwait(false);
}
public async Task Disconnect()
{
await HubConnection.StopAsync().ConfigureAwait(false);
}
public async Task SendMessage(Message message)
{            
await HubConnection.InvokeAsync("SendMessage", message).ConfigureAwait(false);
}
}

-登录后应用程序启动时连接到集线器:

public MainPage()
{
InitializeComponent();                   
MasterBehavior = MasterBehavior.Popover;
//should be home page
MenuPages.Add((int)MenuItemType.Home, (NavigationPage)Detail);
HubService.Connect().ConfigureAwait(true);            
}

-注销时关闭连接

-发送消息时,我调用SendMessage方法:

await HubService.SendMessage(message).ConfigureAwait(true);
OutGoingText = string.Empty;
Messages.Add(message);

现在的问题是当我发送消息并到达:

public async Task SendMessage(Message message)
{            
await HubConnection.InvokeAsync("SendMessage", message).ConfigureAwait(false);
}

抛出这个:

System.InvalidOperationException: 'The 'InvokeCoreAsync' method cannot be called if the connection is not active'

已经尝试使用HubService.Connect((.Wait((,但应用程序仍处于循环中

有人能帮我吗@尼克·科瓦尔斯基。。。

致以最诚挚的问候

我发现问题了!

调用"HubService.Connect((.ConfigureAwait(true(;"时出现问题,这是构造函数中的一个异步方法,因此它不能等待。

public MainPage()
{
InitializeComponent();                   
MasterBehavior = MasterBehavior.Popover;
//should be home page
MenuPages.Add((int)MenuItemType.Home, (NavigationPage)Detail);
HubService.Connect().ConfigureAwait(true);            
}

解决了将调用"HubService.Connect((.ConfigureAwait(true(;"移动到App.xaml.cs并将其放入"OnStart(("方法中的问题:

protected override async void OnStart()
{
await HubService.Connect().ConfigureAwait(true);
}

谢谢大家!

最新更新