作者xa9277178 (楓曦)
看板Programming
標題[請益] C# thread sleep 使用for迴圈問題
時間Mon Aug 22 22:05:04 2016
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;
namespace WindowsFormsApplication11
{
public partial class Form1 : Form
{
Thread sample1;
Thread sample2;
Thread sample3;
Thread sample4;
Thread sample5;
Thread sample6;
public Form1()
{
InitializeComponent();
}
private void _ThreadFunction()
{
Thread.Sleep(8000); //延
遲幾秒
}
private void button1_Click(object sender, EventArgs e)
{
for (int i = 1; i <= 2; i++)
{
string mm = DateTime.Now.ToString("H-m-s");
textBox1.Text = (mm);
sample1 = new Thread(_ThreadFunction);
sample1.Start();
Process.Start(@"C:\Users\wind\Desktop\春泥.mp3");
}
}
上面這段程式碼我擷取到第一個button,我是想做一個計時器,可以每8秒提醒我一次,
為什麼會使用thread來做是因為我一次設計了6個計時器,尷尬地發現sleep的時候
我不能按其他幾個計時器按鈕,原先這樣嘗試是OK的。
當我加入了for之後,我自己的想法裡,經過Start()的時候,不是應該要靜止8秒嗎?
可是我卻發現...他連開兩次春泥(process.start的歌),可是我是希望每8秒循環一次,
放歌出來提醒我,請問我有忽略到哪個部分,懇請大神指導。
順帶一問,其實我只是..想要有類似按鍵精靈那種wait的方法,不要讓我整個
程式卡住,可是網路上的方法千奇百怪,有些根本看不懂,這個方式已經是最簡單
我能理解的了...
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.175.47.235
※ 文章網址: https://www.ptt.cc/bbs/Programming/M.1471874708.A.5AA.html
→ Expsun: UI Thread通常只有一條112.105.222.108 08/23 06:12
→ fo40225: 你開了新的執行緒 在新執行緒設定暫停 61.230.213.158 08/23 09:35
→ fo40225: UI thread還是繼續執行 程式流程在新 61.230.213.158 08/23 09:36
→ fo40225: thread.Start()時就分岔了 61.230.213.158 08/23 09:37
推 joe791023: 可以試試看 await Task.Delay(8000), 220.133.169.73 09/21 23:32
→ joe791023: 但是方法前要加上 async 220.133.169.73 09/21 23:32