Ví dụ: các bạn muốn viết ứng dụng của mình sau khoảng thời gian bao nhiêu giây thì sẽ chạy hàm đó.
Full Code Function SetTimeOut C#:
public void SetTimeout(Action action, int timeout) { var timer = new Timer(); timer.Interval = timeout; timer.Tick += (s,e) => { action(); timer.Stop(); }; timer.Start(); }
Ở phương thức này chúng ta sẽ truyền vào 1 Action và thời gian delay chờ đợi để thực hiện function đó.
Ví dụ: Mình sẽ thiết kế 1 button, khi click vào button đó sau 15 giây thì sẽ hiển thị thông báo hết thời gian, chúng ta sẽ viết như sau
private void btnStart_Click(object sender, EventArgs e) { var action = new Action(() => { MessageBox.Show("Hết thời gian 15s"); }); SetTimeout(action, 15000); }
FULL CODE C#
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; namespace SetTimeOut { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnStart_Click(object sender, EventArgs e) { var action = new Action(() => { MessageBox.Show("Hết thời gian 15s"); }); SetTimeout(action, 15000); } public void SetTimeout(Action action, int timeout) { var timer = new Timer(); timer.Interval = timeout; timer.Tick += (s,e) => { action(); timer.Stop(); }; timer.Start(); } } }
Chúc các bạn thành công với thủ thuật trên
Theo: LapTrinhVB.Net
https://youtu.be/Hmxqj0TVMgw
Trả lờiXóamọi người cùng nhau áp dụng nhé.
Trả lờiXóa