首页 > 解决方案 > UWP 桌面桥应用程序在双击时崩溃

问题描述

我正在开发 UWP 桌面桥应用程序。我已经创建了打包项目并创建了一个用于侧载的应用程序包。当我单击一次应用程序图标时,应用程序启动成功。但是在双击图标时,应用程序崩溃了。

我已经按照以下链接创建了打包项目: https ://docs.microsoft.com/en-us/windows/msix/desktop/desktop-to-uwp-packaging-dot-net 该应用程序只需单击即可正常运行应用程序图标。是不是因为双击时,.exe 被调用了两次,这就是崩溃的原因?

这是后台进程的主要方法

   private static void Main(string[] args)
    {
        try
        {
            connection.AppServiceName = "CommunicationService";
            connection.PackageFamilyName = Windows.ApplicationModel.Package.Current.Id.FamilyName;

            // hook up the connection event handlers
            connection.ServiceClosed += Connection_ServiceClosed;
            connection.RequestReceived += Connection_RequestReceived;

            AppServiceConnectionStatus result = AppServiceConnectionStatus.Unknown;


            // static void Main cannot be async until C# 7.1, so put this on the thread pool
            Task.Run(async () =>
            {
                // open a connection to the UWP AppService
                result = await connection.OpenAsync();

            }).GetAwaiter().GetResult();

            if (result == AppServiceConnectionStatus.Success)
            {
                while (true)
                {

                }
            }
        }
        catch (Exception)
        {
        }
    }

要调用的代码:

    private async Task StartBackgroundProcess()
    {
        try
        {
            // Make sure the BackgroundProcess is in your AppX folder, if not rebuild the solution
            await Windows.ApplicationModel.FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync();
        }
        catch (Exception)
        {
            MessageDialog dialog = new MessageDialog("Rebuild the solution and make sure the BackgroundProcess is in your AppX folder");
            await dialog.ShowAsync();
        }
    }

此外,在包清单内:

<desktop:Extension Category="windows.fullTrustProcess" Executable="BackgroundProcess.exe" />
    <uap:Extension Category="windows.appService">
      <uap:AppService Name="CommunicationService" />
    </uap:Extension>

<rescap:Capability Name="runFullTrust" />

是否有可能避免崩溃问题?

标签: c#xamluwpdesktop-bridge

解决方案


请检查AppService Bridge 示例。它每次创建并启动一个单独的线程以创建一个新的 AppServiceConnection 实例并调用其 OpenAsync 方法。

static void Main(string[] args)
{
    Thread appServiceThread = new Thread(new ThreadStart(ThreadProc));
    appServiceThread.Start();
}

static async void ThreadProc()
{
    connection = new AppServiceConnection();
    connection.AppServiceName = "CommunicationService";
    connection.PackageFamilyName = Windows.ApplicationModel.Package.Current.Id.FamilyName;
    connection.RequestReceived += Connection_RequestReceived;
    AppServiceConnectionStatus status = await connection.OpenAsync();
}

推荐阅读