- [TOOL] Chia sẻ phần mềm thay đổi thông tin cấu hình máy tính
- [C#] Hướng dẫn Export dữ liệu ra file Microsoft Word Template
- [C#] Chia sẻ source code tool kiểm tra domain website
- [C#] Hướng dẫn tạo file PDF sử dụng thư viện QuestPDF
- [C#] Hướng dẫn tạo ứng dụng dock windows giống Taskbar
- [C#] Chia sẻ source code sử dụng Object Listview trên Winform
- [VB.NET] Chia sẻ source code quản lý thu chi mô hình 3 lớp Winform
- [DATABASE] Xóa lịch sử danh sách đăng nhập tài khoản trên SMSS Sqlserver Management Studio
- [C#] Sử dụng FolderBrowserDialog Vista trên Winform
- [DEVEXPRESS] Chia sẻ tool Winform UI Templates Early Access Preview (EAP)
- [C#] Chia sẻ source code Spin Content (Trộn nội dung văn bản theo từ đồng nghĩa) trên Winform
- [VB.NET] Chia sẻ source code lịch âm dương và hẹn lịch nhắc việc
- [C#] Hướng dẫn đọc thông số thiết bị Thiết bị kiểm tra Pin (HIOKI BATTERY HiTESTER BT3562)
- [VB.NET] Hướng dẫn giải captcha sử dụng dịch vụ AZCaptcha API trên winform
- [C#] Hướng dẫn chứng thực đăng nhập ứng dụng bằng vân tay (Finger Print) trên máy tính
- [C#] Color Thief cách xuất màu sắc thiết kế từ hình ảnh
- [C#] Cách tạo bản quyền và cho phép dùng thử ứng dụng Winform
- [C#] Hướng dẫn sử dụng trình duyệt web Chrome convert HTML sang tập tin file PDF
- [C#] Kết nôi điện thoại Android, IOS với App Winform via Bluetooth
- [DATABASE] Cách query cộng trừ dồn dần trong Sqlserver
[C#] Start, Pause Token , CancelSourceToken trong Task Parallelism
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 Start, Pause, Resume và Stop trong Task Parallel C# Winform.
Trong NetFramework, thì Task có hỗ trợ CancelSourceToken, còn PauseTokenSource thì không có hỗ trợ.
Nên chúng ta cần viết thêm hai class PauseToken
và PauseTokenSource
.
Giao diện demo ứng dụng Start, Pause, Resume, Stop Task Parallel C#:
- Tạo Class PauseTokenSource.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace PauseTokenSource
{
class PauseTokenSource
{
private volatile TaskCompletionSource<bool> m_paused;
internal static readonly Task s_completedTask = Task.FromResult(true);
public bool IsPaused
{
get { return m_paused != null; }
set
{
if (value)
{
Interlocked.CompareExchange(
ref m_paused, new TaskCompletionSource<bool>(), null);
}
else
{
while (true)
{
var tcs = m_paused;
if (tcs == null) return;
if (Interlocked.CompareExchange(ref m_paused, null, tcs) == tcs)
{
tcs.SetResult(true);
break;
}
}
}
}
}
public PauseToken Token { get { return new PauseToken(this); } }
internal Task WaitWhilePausedAsync()
{
var cur = m_paused;
return cur != null ? cur.Task : s_completedTask;
}
}
}
2. Tiếp tục tạo thêm Class PauseToken.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PauseTokenSource
{
class PauseToken
{
private readonly PauseTokenSource m_source;
internal PauseToken(PauseTokenSource source) { m_source = source; }
public bool IsPaused { get { return m_source != null && m_source.IsPaused; } }
public Task WaitWhilePausedAsync()
{
return IsPaused ?
m_source.WaitWhilePausedAsync() :
PauseTokenSource.s_completedTask;
}
}
}
3. Viết code cho Form Main ứng dụng Demo Task C#:
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PauseTokenSource
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
PauseTokenSource pts;
CancellationTokenSource cts;
private async void btnStart_Click(object sender, EventArgs e)
{
btnStart.Enabled = false;
btnPause.Enabled = true;
btnStop.Enabled = true;
rbResult.Clear();
cts = new CancellationTokenSource();
pts = new PauseTokenSource();
var tokenSource = cts.Token;
await SomeMethodAsync(tokenSource);
}
public async Task SomeMethodAsync(CancellationToken ct)
{
for (int i = 0; i <= 100; i++)
{
this.BeginInvoke(new Action(()=>
{
rbResult.Text += "i = " + i + "\r\n";
progressBar1.Value = i;
lbl_status.Text = i + "%";
if(i == 100)
{
MessageBox.Show("Finish");
btnStart.Enabled = true;
btnPause.Enabled = false;
btnStop.Enabled = false;
}
}));
if (ct.IsCancellationRequested)
{
break;
}
await Task.Delay(200);
await pts.WaitWhilePausedAsync();
}
}
private void btnPause_Click(object sender, EventArgs e)
{
pts.IsPaused = !pts.IsPaused;
if (pts.IsPaused)
{
btnPause.Text = "Resume";
}
else
{
btnPause.Text = "Pause";
}
}
private void btnStop_Click(object sender, EventArgs e)
{
cts.Cancel();
btnStart.Enabled = true;
btnPause.Enabled = false;
btnStop.Enabled = false;
}
}
}
Các bạn có thể download source code bên dưới về để tham khảo.
Thanks for watching!