Repository navigation
Expand file tree
/
Copy pathFormProgressDialog.cs
More file actions
183 lines (154 loc) · 6.21 KB
/
Copy pathFormProgressDialog.cs
File metadata and controls
183 lines (154 loc) · 6.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SharpTagManager
{
/// <summary>
/// Progress indicator Form
/// Provides a self contained way to run a long processing task without making the app unresponsive
/// while also showing progress and providing a way to cancel the operation
///
/// The work is done on a separate thread, so care must be taken when accessing outside resources
/// Callbacks for completion and cancel are invoked back into the main thread, so they can touch any controls safely
/// </summary>
public partial class FormProgressDialog : Form
{
private CancellationTokenSource _cancellationTokenSource;
private Form _parentForm;
private float _latestProgress;
private string _latestStatus;
private bool _updatePending;
private static void UsageExample()
{
using (var progressDialog = new FormProgressDialog(/*this*/null,"Example task in progress..."))
{
// Run the long-running work in the progress dialog and specify the completion callback
progressDialog.RunTask(LongRunningWork, WorkCompleted, WorkCanceled);
}
void LongRunningWork(FormProgressDialog progress, CancellationToken token)
{
for (int i = 0; i <= 100; i++)
{
// Check if the operation has been canceled
token.ThrowIfCancellationRequested();
// Simulate some work by sleeping for a short time
Thread.Sleep(50);
// Report progress
progress.SetProgress( i / 100.0f);
progress.SetStatus("Doing stuff");
}
}
void WorkCompleted()
{
// This method will be called on the UI thread after the long-running task completes
MessageBox.Show("Work completed successfully!");
// Here you can manipulate form controls, like updating a label, enabling buttons, etc.
}
void WorkCanceled()
{
// This method will be called on the UI thread after the long-running task completes
MessageBox.Show("Work completed successfully!");
// Here you can manipulate form controls, like updating a label, enabling buttons, etc.
}
}
public FormProgressDialog(Form parentForm, string title="Loading...")
{
InitializeComponent();
_parentForm = parentForm;
this.Text = title;
}
public void SetProgress(float progress)
{
_latestProgress = progress;
_updatePending = true;
}
public void SetStatus(string status)
{
_latestStatus = status;
_updatePending = true;
}
public CancellationToken CancellationToken => _cancellationTokenSource.Token;
private void FormProgressDialog_Load(object sender, EventArgs e)
{
}
private void buttonCancel_Click(object sender, EventArgs e)
{
_cancellationTokenSource.Cancel();
}
public void RunTask(Action<FormProgressDialog, CancellationToken> work, Action onCompleted = null, Action onSuccess=null, Action onCancel = null)
{
_cancellationTokenSource = new CancellationTokenSource();
Form invokeForm = this;
if (_parentForm != null)
{
_parentForm.Enabled = false; // Disable the parent form
invokeForm = _parentForm;
}
Task.Run(() =>
{
try
{
work(this,_cancellationTokenSource.Token);
invokeForm.Invoke(new Action(() =>
{
onSuccess?.Invoke(); // Call the completion action on the UI thread
}));
}
catch (OperationCanceledException)
{
SetStatus("Operation canceled.");
invokeForm.Invoke(new Action(() =>
{
onCancel?.Invoke(); // Call the cancel action on the UI thread
}));
}
catch (Exception ex)
{
MessageBox.Show($"Error:\n {ex.Message} \n\nTrace:\n{ex.StackTrace}");
}
finally
{
invokeForm.Invoke(new Action(() =>
{
try
{
if (onCompleted != null)
onCompleted(); // Call the completion action on the UI thread
}
catch (Exception err)
{
MessageBox.Show($"{err.Message}\n\n{err.StackTrace}", "Background task error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if (_parentForm != null) _parentForm.Enabled = true; // Re-enable the parent form
Close();
}
}));
}
});
ShowDialog(); // Show the progress dialog as a modal dialog
}
private void timer1_Tick(object sender, EventArgs e)
{
if (_updatePending)
{
Invoke(new Action(() =>
{
progressBar.Value = (int)Math.Min(_latestProgress * 1000000, 1000000) + 1;
progressBar.Value -= 1; // Hack to skip the animation of the progres bar(makes the bar lag behind actual progress)
labelStatus.Text = _latestStatus;
}));
_updatePending = false;
}
}
}
}