c# - SendMessageAsync 在 Win32 和 UWP 之间通信时随机抛出异常

标签 c# winforms uwp

在我的 UWP 应用程序中,我需要不断地将数据从 WinForms (Win32) 组件发送到 UWP 应用程序,反之亦然。但是,我的 WinForms 组件中有一个奇怪的错误。有时,在启动 WinForm 时,我在调用 await connection.SendMessageAsync(message) 时得到一个 System.InvalidOperationException 说:在意外的时间调用了一个方法 其他时候,它工作得很好。

我的代码:

private async void SendToUWPVoidAsync(object content)
{
    ValueSet message = new ValueSet();
    if (content != "request") message.Add("content", content);
    else message.Add(content as string, "");

    #region SendToUWP

    // if connection isn't inited
    if (connection == null)
    {
        // init
        connection = new AppServiceConnection();
        connection.PackageFamilyName = Package.Current.Id.FamilyName;
        connection.AppServiceName = "NotifyIconsUWP";
        connection.ServiceClosed += Connection_ServiceClosed;

        // attempt connection 
        AppServiceConnectionStatus connectionStatus = await connection.OpenAsync();
    }

    AppServiceResponse serviceResponse = await connection.SendMessageAsync(message);

    // get response
    if (serviceResponse.Message.ContainsKey("content"))
    {
        object newMessage = null;
        serviceResponse.Message.TryGetValue("content", out newMessage);

        // if message is an int[]
        if (newMessage is int[])
        {
            // init field vars
            int indexInArray = 0;
            foreach (int trueorfalse in (int[])newMessage)
            {
                // set bool state based on index
                switch (indexInArray)
                {
                    case 0:
                        notifyIcon1.Visible = Convert.ToBoolean(trueorfalse);
                        break;
                    case 1:
                        notifyIcon2.Visible = Convert.ToBoolean(trueorfalse);
                        break;
                    case 2:
                        notifyIcon3.Visible = Convert.ToBoolean(trueorfalse);
                        break;
                    default:
                        break;
                }
                indexInArray++;
            }
        }
    }
    #endregion
}

方法是这样调用的:

private void TCheckLockedKeys_Tick(object sender, EventArgs e)
{
    ...

    if (statusesChanged)
    {
        // update all bools
        bool1 = ...;
        bool2 = ...;
        bool3 = ...;

        // build int[] from bool values
        int[] statuses = new int[] { Convert.ToInt32(bool1), Convert.ToInt32(bool2), Convert.ToInt32(bool3) };

        // update UWP sibling
        SendToUWPVoidAsync(statuses);
    }

    // ask for new settings
    SendToUWPVoidAsync("request");
}

TCheckLockedKeys_Tick.Interval 设置为 250 毫秒。

有没有办法在 WinForm 组件不退出但仍建立重要通信路径的情况下防止或正确处理此异常?

有什么想法吗?

谢谢

最佳答案

好的,我找到了解决方案。人们可能实际上将其称为解决方法。

在我的 WinForm 中,我将代码更改如下:

AppServiceResponse serviceResponse = await connection.SendMessageAsync(message);

到:

AppServiceResponse serviceResponse = null;
try
{
    // send message
    serviceResponse = await connection.SendMessageAsync(message);
}
catch (Exception)
{
     // exit 
     capsLockStatusNI.Visible = false;
     numLockStatusNI.Visible = false;
     scrollLockStatusNI.Visible = false;

     Application.Exit();
 }

我还更改了我的 App.xaml.cs 文件中的代码:

private async void OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
{
    if (this.appServiceDeferral != null)
    {
        // Complete the service deferral.
        this.appServiceDeferral.Complete();
    }
}

到:

private async void OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
{
    if (reason == BackgroundTaskCancellationReason.SystemPolicy)
    {
        // WinForm called Application.Exit()
        await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync();
    }
    if (this.appServiceDeferral != null)
    {
        // Complete the service deferral.
        this.appServiceDeferral.Complete();
    }
}

我知道我所做的只是,从技术上讲,重新启动表单直到它成功,这并不是解决问题的完全正确方法。但是,它有效。

关于c# - SendMessageAsync 在 Win32 和 UWP 之间通信时随机抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49735833/

相关文章:

c# - 带有控件的表单级别的 KeyPress

c# - 是否可以使用 C# 4 中的动态方法在每次调用时返回不同的数据类型?

c# - 如何用c#制作两个透明层?

c# - UWP - 语言的变化

xaml - UWP xaml : How to display a button with icon and text in it?

c# - 按长度拆分字符串

c# - 在 C# 中检测两个 json 文件之间的差异

c# - 用户输入 - 数据验证

c# - 为什么 Application.Current == null 在 WinForms 应用程序中?

c# - .netstandard 库和 UniversalApiContract