回覆列表
  • 1 # 使用者834195712159

    程式碼示例:

    public partial class Form1 : Form

    {

    private delegate void FlushClient();//代理

    public Form1()

    {

    InitializeComponent();

    }

    private void Form1_Load(object sender, EventArgs e)

    {

    Thread thread = new Thread(CrossThreadFlush);

    thread.IsBackground=true;

    thread.Start();

    }

    private void CrossThreadFlush()

    {

    //將代理繫結到方法

    FlushClient fc = new FlushClient(ThreadFuntion);

    this.BeginInvoke(fc);//呼叫代理

    }

    private void ThreadFuntion()

    {

    while (true)

    {

    this.textBox1.Text = DateTime.Now.ToString();

    Thread.Sleep(1000);

    }

    }

    }

    using System;

    using System.Collections.Generic;

    using System.ComponentModel;

    using System.Data;

    using System.Drawing;

    using System.Linq;

    using System.Text;

    using System.Windows.Forms;

    using System.Threading;

    namespace WindowsFormsApplication4

    {

    public partial class Form1 : Form

    {

    private delegate void FlushClient(); //代理

    Thread thread = null;

    int counter = 0;

    public Form1()

    {

    InitializeComponent();

    }

    private void button1_Click(object sender, EventArgs e)

    {

    this.listBox1.Items.Clear();

    button1.Enabled = false;

    thread = new Thread(CrossThreadFlush);

    thread.IsBackground = true;

    thread.Start();

    }

    private void button2_Click(object sender, EventArgs e)

    {

    thread.Suspend();

    button1.Enabled = true;

    }

    private void CrossThreadFlush()

    {

    while (true)

    {

    //將sleep和無限迴圈放在等待非同步的外面

    Thread.Sleep(1000);

    ThreadFunction();

    }

    }

    private void ThreadFunction()

    {

    if (this.listBox1.InvokeRequired)//等待非同步

    {

    FlushClient fc = new FlushClient(ThreadFunction);

    this.Invoke(fc); //透過代理呼叫重新整理方法

    }

    else

    {

    counter += 1;

    this.label1.Text = counter.ToString();

    this.listBox1.Items.Add(System.DateTime.Now.ToString());

    }

    }

    }

    }

  • 中秋節和大豐收的關聯?
  • 下聯:鬢中白髮滿清霜,如何對上聯?