线程+GDI的典型应用

本文介绍了一个使用C#和Windows Forms绘制动态正弦曲线的应用实例。通过创建后台线程来逐段绘制正弦曲线,避免了界面卡顿的问题,并介绍了如何利用线程改善用户体验。
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Text;
  7. using System.Windows.Forms;
  8. using System.Threading; //增加线程命名空间
  9. namespace 正弦曲线
  10. {
  11.     public partial class Form1 : Form
  12.     {
  13.         public Form1()
  14.         {
  15.             InitializeComponent();
  16.         }
  17.         private void Form1_Paint(object sender, PaintEventArgs e)
  18.         {
  19.            Thread t1 = new Thread(new ThreadStart(MyDraw));  //定义线程
  20.            t1.IsBackground = true;  //设置线程为后台线程,运行时不影响主线程
  21.            t1.Start();  //启动线程
  22.           // MyDraw();
  23.         }
  24.         private void MyDraw()
  25.         {
  26.             //通过许多短的直线构建出正弦曲线
  27.             float x1, x2, y1, y2;
  28.             x1 = 0;
  29.             y1 = 300;
  30.             Graphics g = this.CreateGraphics();
  31.             Pen p = new Pen(Color.Red);
  32.             for (int i = 0; i < this.Width; i += 5)
  33.             {
  34.                 //得到直线的终点
  35.                 x2 = x1 + 5;
  36.                 y2 = (float)(-50 * Math.Sin(x2 / 60) + 300);
  37.                 //画直线
  38.                 g.DrawLine(p, x1, y1, x2, y2);
  39.                 //画完直线后,将终点当起点,准备画下一条直线
  40.                 x1 = x2;
  41.                 y1 = y2;
  42.                 Thread.Sleep(100);   //实现暂停功能,每次循环暂停100毫秒
  43.             }
  44.             g.Dispose();
  45.         }
  46.     }
  47. }

在上面的 Form1_Paint()方法中,如果把前三行注释掉,而只使用第四行代码,一样可以实现画图,但你会明显感觉到窗体被卡死了。这就是使用线程的好处.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值