【发布时间】:2018-04-09 14:50:39
【问题描述】:
在我的 UWP 应用中,我需要不断地从 WinForms (Win32) 组件向 UWP 应用发送数据,反之亦然。但是,我的 WinForms 组件中有一个奇怪的错误。有时,在启动 WinForm 时,我在调用 await connection.SendMessageAsync(message) 时收到 System.InvalidOperationException 说:A method was called at an unexpected time 其他时候,它运行良好。
我的代码:
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 组件但仍建立重要的通信路径?
有什么想法吗?
谢谢
【问题讨论】:
-
您的 Winforms 应用程序是否包含在与 UWP 应用程序相同的包中?您是否跟踪 ServiceClosed 事件(在 Winforms 进程中)和 TaskCanceled 事件(在 UWP 进程中)以了解连接消失?
-
在上一次尝试完成 SendMessageAsync() 之前被您的 Tick 事件处理程序重新激活肯定不是很高兴。在应用程序启动或机器负载过重时,超过 250 毫秒的延迟并不少见。避免重入的一种简单方法是禁用计时器并在异步完成后重新启用它。或者使用 Task.Delay 而不是计时器。
-
@StefanWickMSFT 是的,两者都被跟踪并且它们在同一个包中
-
@StefanWickMSFT 感谢您提醒我有关
TaskCanceled事件