我有一个主机应用程序服务的主机UWP应用程序,在其App.xaml.cs中,我有以下代码: private BackgroundTaskDeferral _appServiceDeferral; private AppServiceConnection _appServiceConnection; protected override void OnBackgroundActivated(BackgroundActivatedEventArgs args) { base.OnBackgroundActivated(参数); if(args.TaskInstance.TriggerDetails是AppServiceTriggerDetails) { _appServiceDeferral = args.TaskInstance.GetDeferral(); args.TaskInstance.Canceled + = OnAppServicesCanceled; AppServiceTriggerDetails details = args.TaskInstance.TriggerDetails as AppServiceTriggerDetails; _appServiceConnection = details.AppServiceConnection; _appServiceConnection.RequestReceived + = Connection_RequestReceived; _appServiceConnection.ServiceClosed + = AppServiceConnection_ServiceClosed; } }
我的主机应用程序是一个UWP应用程序,它会在某个时间启动win32应用程序,Win32是一个客户端应用程序。我有以下Win32应用程序代码:
connection = new AppServiceConnection(); connection.AppServiceName =“MyTestCommunicationService”; connection.PackageFamilyName = Windows.ApplicationModel.Package.Current.Id.FamilyName; connection.RequestReceived + = ClientConnection_RequestReceived; connection.ServiceClosed + = Connection_ServiceClosed;
var status = await connection.OpenAsync().AsTask();
在UWP主机应用程序中,我可以向win32应用程序发送消息:
if (_appServiceConnection!= null)
{
ValueSet valueSet = new ValueSet();
valueSet.Add("Command", dataContent);
AppServiceResponse response = await _appServiceConnection.SendMessageAsync(valueSet);
_isSuccess = response.Status == AppServiceResponseStatus.Success;
}
我看到很多示例客户端向app connection的主机应用程序发送请求,主机应用程序处理请求。我想知道我的代码是在主机应用程序和win32应用程序之间进行双向通信的正确方法。我测试了它正在运行的代码,但想了解有关应用服务连接的最佳实践。
答案 0 :(得分:3)
是的,AppServiceConnection是一个双向通信管道。双方都有一个AppServiceConnection实例,他们可以使用它来向另一方发起请求,以及接收来自另一方的请求。