现在我很欣赏这个故事的寓意是“不要占用 UI 线程”,但我们试图通过尽可能长时间保持 UI 线程上的东西来亲吻,但我认为我们刚刚达到了临界点,我们正在将不得不改变我们的设计。
但无论如何......我在我们的设备上注意到的一些在桌面上不会发生的事情:当你占用 UI 线程时,它会丢弃键。这是一个显示问题的非常简单的应用程序。
using System;
using System.Windows.Forms;
namespace DeviceApplication14
{
public partial class Form1 : Form
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[MTAThread]
static void Main()
{
Application.Run(new Form1());
}
private int ctr;
public Form1()
{
InitializeComponent();
KeyPreview = true;
KeyDown += Form1_KeyDown;
}
void Form1_KeyDown(object sender, KeyEventArgs e)
{
for (int i = 0; i < 1000000; i++)
{
}
ctr++;
button1.Text = ctr.ToString();
}
private void button2_Click(object sender, EventArgs e)
{
ctr = 0;
button1.Text = ctr.ToString();
}
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(235, 137);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(329, 239);
this.button1.TabIndex = 0;
this.button1.Text = "button1";
//
// button2
//
this.button2.Location = new System.Drawing.Point(62, 291);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(72, 20);
this.button2.TabIndex = 1;
this.button2.Text = "Clear";
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.AutoScroll = true;
this.ClientSize = new System.Drawing.Size(638, 455);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
private Button button1;
private Button button2;
}
}
当我在我的自定义框上运行它时,我可以连续按四个键,但我的 ctr 只增加 2。如果我然后添加几个零(以补偿桌面更快的速度)并在桌面上运行它,我会得到所有的键。
这里发生了什么?