search
尋找貓咪~QQ 地點 桃園市桃園區 Taoyuan , Taoyuan

C# thread02 – jashliao部落格

C# thread02
功能:
01.主要實作如何利用類別(ThreadWithState)方式傳遞參數給執行緒

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;//step 01
namespace CS_thread
{
public class ThreadWithState
{
private double value;
public ThreadWithState(double number)
{
value = number;
}
public void ThreadProc()
{
while (true)
{
Form1.m_dblcount += this.value;
Thread.Sleep(3000);
}
}
}
public partial class Form1 : Form
{
public static double m_dblcount;
private Thread m_Thread = null;
private Thread m_ClassThread = null;
private ThreadWithState tws;
delegate void SetTextCallback(string text);
public Form1()
{
InitializeComponent();
m_dblcount = 0.0;
}
public void threadFun()
{
while (true)
{
//Form1.m_dblcount += 1.0;
String StrBuf;
StrBuf=Convert.ToString(Form1.m_dblcount);
SetText(StrBuf);
Thread.Sleep(3000);
}
}
public void SetText(string text)
{
if (this.textBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.textBox1.Text = text;
}
}
private void button1_Click(object sender, EventArgs e)
{
m_Thread = new Thread(new ThreadStart(threadFun));
m_Thread.Start();
tws = new ThreadWithState(20.0);
m_ClassThread= new Thread(new ThreadStart(tws.ThreadProc));
m_ClassThread.Start();
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if (m_Thread.IsAlive)
{
m_Thread.Abort();
}
if (m_ClassThread.IsAlive)
{
m_ClassThread.Abort();
}
}
}
}

 


 

 




熱門推薦

本文由 jashliaoeuwordpress 提供 原文連結

寵物協尋 相信 終究能找到回家的路
寫了7763篇文章,獲得2次喜歡
留言回覆
回覆
精彩推薦