gpt4 book ai didi

c# - 在 Xamarin Forms 中等待 MessagingCenter

转载 作者:太空宇宙 更新时间:2023-11-03 19:00:09 25 4
gpt4 key购买 nike

我尝试使用我的 ViewModel 中的 MessagingCenter 实现 MVVM。我收到以下错误,因为多个线程收到相同的消息“ClearStackLayout”并且不等待彼此的回调结束:

Index was outside the bounds of the array.

这是我的查看代码:

public partial class LibraryChoicePage : DefaultBackgroundPage {

private Object thisLock = new Object();

public LibraryChoicePage() {
InitializeComponent();

/* ClearStackLayout */
MessagingCenter.Subscribe<LibraryChoiceViewModel>(this, "ClearStackLayout", (sender) => {
lock (thisLock) {
this._choices.Children.Clear();
}
});

/* AddToStackLayout */
MessagingCenter.Subscribe<LibraryChoiceViewModel, View>(this, "AddToStackLayout", (sender, arg) => {
lock (thisLock) {
this._choices.Children.Add(arg);
}
});

}

}

最佳答案

第一件事是总是在 UI 线程上调用 StackLayout.Children.Clear|AddiOS 不喜欢从主 UI 线程中移除 UIView subview ,它会抛出异常,甚至会导致 native 崩溃

这就是我如何序列化消息调用:

var semaphone = new SemaphoreSlim(1);
MessagingCenter.Subscribe<object>(this, "ClearStackLayout", async (sender) =>
{
await semaphone.WaitAsync();
Device.BeginInvokeOnMainThread(() =>
{
_choices.Children.Clear();
});
semaphone.Release();
});

MessagingCenter.Subscribe<object, View>(this, "AddToStackLayout", async (sender, arg) =>
{
await semaphone.WaitAsync();
Device.BeginInvokeOnMainThread(() =>
{
_choices.Children.Add(arg);
});
semaphone.Release();
});

注意:try/finally 应该包装 SemaphoreSlim.Release 和一个 catch 以执行 add 所需的任何恢复器代码/清除失败。

UIUnit 并行测试方法:

Random random = new Random();
var tasks = new List<Task>();
for (int i = 0; i < 50; i++)
{
if (random.NextDouble() > .1)
tasks.Add(Task.Factory.StartNew(() => { AddLayout(); }));
else
tasks.Add(Task.Factory.StartNew(() => { ClearLayout(); }));
}
var completed = Task.Factory.ContinueWhenAll(tasks.ToArray(), (messagecenterTasks) => {
foreach (var task in messagecenterTasks)
{
if (task.Status == TaskStatus.Faulted)
{
D.WriteLine("Faulted:");
D.WriteLine($" {task.Exception.Message}");
}
}
}).Wait(1000);
if (!completed)
D.WriteLine("Some tasks did not complete in time allocated");

注意:AddLayout/ClearLayout 是 AddToStackLayoutClearStackLayoutMessageCenter.Send 的方法包装。/p>

关于c# - 在 Xamarin Forms 中等待 MessagingCenter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37486027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com