110,539
社区成员
发帖
与我相关
我的任务
分享
public partial class Form1 : Form
{
Point fa = new Point(-120, -80);
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Thread thr = new Thread(showpic);
thr.Start();
}
void showpic()
{
PictureBox picb = new PictureBox();
picb.ImageLocation = "picture\\IMG_20181014_100220.jpg";
picb.Location = fa;
picb.Size = new Size(120, 80);
picb.SizeMode = PictureBoxSizeMode.Zoom;
while(true)
{
picb.Location = new Point(picb.Location.X + 16, picb.Location.Y - 9);
if (picb.Location.X > 1920)
picb.Location = fa;
Thread.Sleep(50);
}
}
}
while(true){
Thread.Sleep(1000);
xxx业务代码;
}
但是如果你的程序是下面这种写法,你的程序就可以对超过10个用户提供服务,因为在await的时候,你的线程已经被暂时释放了,可以给其它用户提供服务,等时间到了,再重新分配一个线程,回来处理你的后续业务代码:
while(true){
await Task.Delay(1000);
xxx业务代码;
}
while(true)
{
abc.Localtion = 新的坐标位置;
Sleep(100);
}
这类死循环代码。接下来,知道这是个坑,就开始觉得线程是个好东西了,满脑子只有线程概念了。
其实早期的 VB 等等工具,以及大量的游戏软件,都是单线程的,都在 UI 主线程就能编写复杂的、世界流行的各种游戏。学过 UI 设计知识的编程者知道用 Timer 来控制游戏流程的每一帧的动做,这就是交互式程序基本概念,不需要纠结子线程。有了这类设计概念,懂得了交互世界的基本道理。而什么“多线程”此时并不重要。private async void Form1_Load(object sender, EventArgs e)
{
var label = new Label();
this.Controls.Add(label);
void 设置方向(out int a, out int b)
{
var rnd = new Random();
a = (int)(rnd.NextDouble() * 50) - 25;
b = (int)(rnd.NextDouble() * 50) - 25;
}
设置方向(out int x, out int y);
while (true)
{
label.Text = DateTime.Now.ToString("mm:ss");
label.Top += y;
label.Left += x;
if (label.Left >= 0 && label.Left <= this.ClientSize.Width && label.Top >= 0 && label.Top <= this.ClientSize.Height)
await Task.Delay(500);
else
{
label.Top -= y;
label.Left -= x;
设置方向(out x, out y);
}
}
}
但是语法是小伎俩,关键是基本的理念。一个语法学起来可能需要1分钟,而一个理念需要你学习5年。private async void Form1_Load(object sender, EventArgs e)
{
var label = new Label();
this.Controls.Add(label);
var rnd = new Random();
var x = (int)(rnd.NextDouble() * 50) - 25;
var y = (int)(rnd.NextDouble() * 50) - 25;
while (true)
{
label.Text = DateTime.Now.ToString("mm:ss");
label.Top += y;
label.Left += x;
if (label.Left >= 0 && label.Left <= this.ClientSize.Width && label.Top >= 0 && label.Top <= this.ClientSize.Height)
await Task.Delay(500);
else
{
label.Top -= y;
label.Left -= x;
x = (int)(rnd.NextDouble() * 50) - 25;
y = (int)(rnd.NextDouble() * 50) - 25;
}
}
}
这里跟什么线程没有直接关系。这里最主要地是,在 Task.Delay 语句执行时,方法 Form_Load 就已经结束了;然后500毫秒之后执行到 label.Text = DateTim.... 语句时,是异步调用的。这其实是基于“事件发生时才回调委托”的概念,要知道交互操作是异步编程的,而不是阻塞的概念。Controls.Add(picb);
2.while循环内嵌Sleep是不对的,你可以使用timer:
Timer timer = new Timer
{
Interval = 50,
Enabled = true
};
timer.Tick += timer1_Tick;
private void timer1_Tick(object sender, System.EventArgs e)
{
picb.Location = new Point(picb.Location.X + 16, picb.Location.Y - 9);
if (picb.Location.X > 1920)
picb.Location = fa;
}
3.Y坐标一直在减,一直在form外 怎么显示?