我的Xamarin iOS应用程序出现线程/睡眠问题。我想创造一个简单的游戏,一种记忆游戏。按下开始按钮时,将有4个按钮可以更改字体。从1开始,然后是2,依此类推。问题是我希望在显示按钮的方法中暂停一下,因为用户需要看几秒钟后更改的颜色。我认为多线程直接赶上下一个任务,所以睡眠消失了:(如何解决这个问题?谢谢!
代码:
partial void btnStart (NSObject sender)
{
teller++;
InvokeOnMainThread( ()=> { for (int i = 0; i < teller; i++) {
String randomGetal = randomizer();
Lijst.Add(new Opslag() {nummerGetal = teller, getal = randomGetal});
ThreadPool.QueueUserWorkItem(o => InvokeOnMainThread(() => {ButtonColor(randomGetal);}));
};
});
lblRandom1.Text = Lijst.Count.ToString();
}
public void ClearButton()
{
btnA.SetTitleColor (UIColor.Green, UIControlState.Normal);
btnB.SetTitleColor (UIColor.Green, UIControlState.Normal);
btnC.SetTitleColor (UIColor.Green, UIControlState.Normal);
btnD.SetTitleColor (UIColor.Green, UIControlState.Normal);
}
public void ButtonColor(string a)
{
if (a == "A") {
btnA.SetTitleColor (UIColor.Magenta, UIControlState.Normal);
Thread.Sleep(2000);
ClearButton ();
}
if (a == "B") {
btnB.SetTitleColor (UIColor.Magenta, UIControlState.Normal);
Thread.Sleep(2000);
ClearButton ();
}
if (a == "C") {
btnC.SetTitleColor (UIColor.Magenta, UIControlState.Normal);
Thread.Sleep(2000);
ClearButton ();
}
if (a == "D") {
btnD.SetTitleColor (UIColor.Magenta, UIControlState.Normal);
Thread.Sleep(2000);
ClearButton ();
}
}
public string randomizer()
{
int randomNummer = random.Next (0, 4);
if (randomNummer == 0)
return "A";
if (randomNummer == 1)
return "B";
if (randomNummer == 2)
return "C";
if (randomNummer == 3)
return "D";
else
return "Empty";
}
}
public class Opslag
{
public int nummerGetal {get;set;
}
public string getal {
get;
set;
}
}
}
答案 0 :(得分:2)
我和Xamarin Android有类似的问题。 Thread.Sleep()不起作用:
- 都不是来自System.Threading.Thread.Sleep()
- 也不是Java.Lang.Thread.Sleep()
花了2小时试图解决问题 发现above answer,但有点复杂,决定提炼核心问题。
<强>解决方案强>
替换'基于线程'的睡眠,就像这里:
DoSth() {
Thread newThread = new Thread(new ThreadStart(DoWork));
newThread.Start();
}
void DoWork() {
Thread.Sleep(5000);
// do sth after 5 secs
}
使用'基于异步的'方法:
DoSth() {
DoWorkAsync();
}
async void DoWorkAsync() {
await Task.Delay(5000);
// do sth after 5 secs
}
顺便说一句。只有在应用程序启动后非常小的问题才会出现问题。
答案 1 :(得分:1)
我知道你可以使用它,但这是一个简化代码的快速建议:
private UIButton[] buttons;
private Random random;
public override void ViewDidLoad()
{
base.ViewDidLoad ();
this.buttons = new [] { btnA, btnB, btnC, btnD };
this.random = new Random ();
// put in an event handler to fire up ButtonColor
}
private async void ButtonColor()
{
var r = random.Next (0, this.buttons.Length);
if (r < this.buttons.Length)
{
var button = this.buttons [r];
var curColor = button.TitleColor(UIControlState.Normal);
button.SetTitleColor(UIColor.Magenta, UIControlState.Normal);
await Task.Delay (2000);
button.SetTitleColor(curColor, UIControlState.Normal);
}
}