NEWS

[C#] Hướng dẫn sử dụng SetTimeOut trên Winform like Javascript

[C#] Hướng dẫn sử dụng SetTimeOut trên Winform like Javascript
Đăng bởi: Thảo Meo - Lượt xem: 4643 08:09:04, 04/08/2022DEVEXPRESS   In bài viết

Xin chào các bạn, bài viết hôm nay mình sẻ tiếp tục hướng dẫn các bạn cách viết hàm SetTimeOut trên C# winform, giống hàm SetTimeOut trên javascript.

[C#] Function SetTimeout in Winform

set_time_out_csharp

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 đó.

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);
}

set_time_out-function

Full source 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();
        }
    }
}

Thanks for watching!

DOWNLOAD SOURCE

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[C#] Hướng dẫn sử dụng SetTimeOut trên Winform like Javascript
Đăng bởi: Thảo Meo - Lượt xem: 4643 08:09:04, 04/08/2022DEVEXPRESS   In bài viết

CÁC BÀI CÙNG CHỦ ĐỀ

Đọc tiếp
.