Trong bài học này, Kteam sẽ Giới thiệu đến bạn Khung WPF Multi Task và cách sử dụng khung này trong lập trình Selenium, giả lập, liên quan đa luồng và cần giao diện.
Nội dung:
Để đọc hiểu bài này tốt nhất các bạn nên có kiến thức cơ bản về phần:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WPF_Multi_Task.ViewModel;
namespace WPF_Multi_Task
{
///<summary>/// Interaction logic for MainWindow.xaml///</summary>publicpartialclass MainWindow : Window
{
MainViewModel ViewModel;
publicMainWindow()
{
InitializeComponent();
}
privatevoidWindow_Loaded(object sender, RoutedEventArgs e)
{
this.DataContext = ViewModel = new MainViewModel();
}
privatevoidWindow_Closed(object sender, EventArgs e)
{
ViewModel.SaveData();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WPF_Multi_Task.ViewModel;
namespace WPF_Multi_Task.Model
{
publicclass SettingData : BaseViewModel
{
privateint _TotalData;
publicint TotalData
{
get => _TotalData;
set
{
_TotalData = value;
OnPropertyChanged();
}
}
}
}
using Newtonsoft.Json;
using OpenQA.Selenium.Chrome;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using WPF_Multi_Task.Model;
namespace WPF_Multi_Task.ViewModel
{
publicclass MainViewModel : BaseViewModel
{
#region Propertiesprivate SettingData _SettingData;
public SettingData SettingData { get => _SettingData; set { _SettingData = value; OnPropertyChanged(); } }
private ObservableCollection<ProfileDetail> _Profiles;
public ObservableCollection<ProfileDetail> Profiles
{
get => _Profiles;
set
{
_Profiles = value;
OnPropertyChanged();
}
}
#endregionpublicMainViewModel()
{
FirstLoad();
LoadCommand();
}
#region CMDpublic ICommand AddData_CMD { get; set; }
public ICommand PauseProfile_CMD { get; set; }
public ICommand ResumeProfile_CMD { get; set; }
public ICommand StartProfile_CMD { get; set; }
public ICommand DeleteProfile_CMD { get; set; }
public ICommand CreateProfile_CMD { get; set; }
public ICommand StartAll_CMD { get; set; }
public ICommand StopAll_CMD { get; set; }
public ICommand StopProfile_CMD { get; set; }
public ICommand DeleteAll_CMD { get; set; }
public ICommand CloseAll_CMD { get; set; }
public ICommand OpenDriver_CMD { get; set; }
public ICommand CloseDriver_CMD { get; set; }
#endregion#region Methodvoid FirstLoad()
{
LoadSavedData();
}
void LoadCommand()
{
StopProfile_CMD = new RelayCommand<ProfileDetail>((p) => { return p != null && Profiles != null && Profiles.Contains(p); }, (p) => { StopProfile(p); });
AddData_CMD = new RelayCommand<ProfileDetail>((p) => { returntrue; }, (p) => { Add500Row(); });
PauseProfile_CMD = new RelayCommand<ProfileDetail>((p) => { return p != null && Profiles != null && Profiles.Contains(p); }, (p) => { PauseProfile(p); });
ResumeProfile_CMD = new RelayCommand<ProfileDetail>((p) => { return p != null && Profiles != null && Profiles.Contains(p); }, (p) => { ResumeProfile(p); });
StartProfile_CMD = new RelayCommand<ProfileDetail>((p) => { return p != null && Profiles != null && Profiles.Contains(p); }, (p) => { StartProfile(p); });
DeleteProfile_CMD = new RelayCommand<ProfileDetail>((p) => { return p != null && Profiles != null && Profiles.Contains(p); }, async (p) =>{ StopProfile(p); await DeleteProfile(p);});
CreateProfile_CMD = new RelayCommand<object>((p) => { returntrue; }, (p) => { CreateProfile(); });
StartAll_CMD = new RelayCommand<ProfileDetail>((p) => { return Profiles != null; }, (p) => { StartAll(); });
StopAll_CMD = new RelayCommand<ProfileDetail>((p) => { return Profiles != null; }, (p) => { StopAll(); });
DeleteAll_CMD = new RelayCommand<ProfileDetail>((p) => { return Profiles != null; }, (p) => { DeleteAll(); });
CloseAll_CMD = new RelayCommand<ProfileDetail>((p) => { returntrue; }, (p) => { CloseAllDriver(); });
OpenDriver_CMD = new RelayCommand<ProfileDetail>((p) => { return p != null; }, (p) => { p.StartTask(() => { OpenDriver(p); }, null,null); });
CloseDriver_CMD = new RelayCommand<ProfileDetail>((p) => { return p != null; }, (p) => { p.StartTask(() => { CloseDriver(p); }, null, null); });
}
void Demo()
{
MessageBox.Show("DDDDD");
}
void StopProfile(ProfileDetail p)
{
p.Status = "Being stop";
p.StopTask();
p.Status = "Stop";
}
asyncvoid PauseProfile(ProfileDetail p)
{
if (await p.PauseTask())
{
p.Status = "Paused";
}
}
asyncvoid ResumeProfile(ProfileDetail p)
{
if (await p.ResumeTask())
{
p.Status = "Resumed";
}
}
void StartAll()
{
StartTask(() => {
foreach (var item in Profiles)
{
StartProfile(item);
}
}, null, null);
}
void CloseAllDriver()
{
StartTask(() => {
foreach (var item in Profiles)
{
StopProfile(item);
CloseDriver(item);
}
}, null, null);
}
void DeleteAll()
{
StartTask(async() => {
while (Profiles.Count > 0)
{
var item = Profiles.First();
StopProfile(item);
await DeleteProfile(item);
}
}, null, null);
}
void StopAll()
{
StartTask(() => {
foreach (var item in Profiles)
{
StopProfile(item);
}
}, null, null);
}
void Add500Row()
{
StartTask(() => {
for (int i = 0; i < SettingData.TotalData; i++)
{
CreateProfile(i + "");
}
}, null, null);
}
void OpenDriver(ProfileDetail p)
{
CloseDriver(p);
p.Driver = new ChromeDriver();
}
void CloseDriver(ProfileDetail p)
{
if (p.Driver != null)
{
try
{
p.Driver.Quit();
}
catch
{
}
}
}
void StartProfile(ProfileDetail p)
{
CancellationTokenSource sourceToken = new CancellationTokenSource();
PauseTokenSource pauseToken = new PauseTokenSource();
var ct = p.StartTask(async () =>
{
OpenDriver(p);
p.Driver.Navigate().GoToUrl("https://howkteam.vn/");
while (true)
{
p.Status = $"Working...{DateTime.Now.Second}";
p.Driver.Navigate().GoToUrl("https://howkteam.vn/learn");
await Task.Delay(TimeSpan.FromSeconds(5));
try
{
sourceToken.Token.ThrowIfCancellationRequested();
}
catch
{
return;
}
await pauseToken.Token.PauseIfRequestedAsync();
p.Driver.Navigate().GoToUrl("https://howkteam.vn/question");
await Task.Delay(TimeSpan.FromSeconds(5));
try
{
sourceToken.Token.ThrowIfCancellationRequested();
}
catch
{
return;
}
await pauseToken.Token.PauseIfRequestedAsync();
}
}, sourceToken, pauseToken);
}
async Task DeleteProfile(ProfileDetail p)
{
p.Status = $"Deleting Profile";
await Application.Current.Dispatcher.InvokeAsync(new Action(() =>
{
p.Status = $"Removing";
Profiles.Remove(p);
UpdateProfileIndex();
}));
}
void UpdateProfileIndex()
{
if (Profiles == null || Profiles.Count == 0)
{
return;
}
int i = 0;
foreach (var item in Profiles)
{
item.Index = ++i;
}
}
ProfileDetail CreateProfile(string profileName = null)
{
if(Profiles == null)
{
Profiles = new ObservableCollection<ProfileDetail>();
}
var profile = new ProfileDetail() { Name = profileName, Status = "Created" };
Application.Current.Dispatcher.InvokeAsync(new Action(() =>
{
Profiles.Add(profile);
UpdateProfileIndex();
}));
return profile;
}
void LoadSavedData()
{
try
{
var text = File.ReadAllText("Saved.txt");
SettingData = JsonConvert.DeserializeObject<SettingData>(text);
}
catch
{
}
if (SettingData == null)
{
SettingData = new SettingData();
SettingData.TotalData = 100;
}
}
publicvoidSaveData()
{
try
{
File.WriteAllText("Saved.txt", JsonConvert.SerializeObject(SettingData));
}
catch { }
}
#endregion
}
}
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
Kết luận
Qua bài học này, bạn đã nắm được Cách sử dụng Multi Task và đã biết được những kinh nghiệm để tùy chỉnh nó vào dự án cá nhân.
Cảm ơn các bạn đã theo dõi bài viết. Hãy để lại bình luận hoặc góp ý của mình để phát triển bài viết tốt hơn. Đừng quên “Luyện tập – Thử thách – Không ngại khó”.
Tải xuống
Tài liệu
Nhằm phục vụ mục đích học tập Offline của cộng đồng, Kteam hỗ trợ tính năng lưu trữ nội dung bài học Multi Task với WPF trong C# dưới dạng file PDF trong link bên dưới.
Ngoài ra, bạn cũng có thể tìm thấy các tài liệu được đóng góp từ cộng đồng ở mục TÀI LIỆU trên thư viện Howkteam.com
Đừng quên like và share để ủng hộ Kteam và tác giả nhé!
Project
Nếu việc thực hành theo hướng dẫn không diễn ra suôn sẻ như mong muốn. Bạn cũng có thể tải xuống PROJECT THAM KHẢO ở link bên dưới!
Thảo luận
Nếu bạn có bất kỳ khó khăn hay thắc mắc gì về khóa học, đừng ngần ngại đặt câu hỏi trong phần bên dưới hoặc trong mục HỎI & ĐÁP trên thư viện Howkteam.com để nhận được sự hỗ trợ từ cộng đồng.
Với mong muốn mang đến kiến thức chất lượng, miễn phí cho mọi người, với tâm huyết phá bỏ rào cản kiến thức từ việc giáo dục thu phí. Tôi đã cùng đội ngũ Kteam đã lập nên trang website này để thế giới phẳng hơn.
Hãy cùng chúng tôi lan tỏa kiến thức đến cộng đồng!
Anh Long ơi, em muốn hỏi chút. Trong khi code thì làm sao để mình tư duy được là nên tổ chức code như thế nào ạ. Ví dụ như trong bài này, làm sao để anh có thể tư duy được là sẽ khai báo và quản lý ChromeDriver trong class ProfileDetail, mà không phải là
khai báo ở ngoài ạ. Em cảm ơn anh.
có bác nào cho e xin đoạn code mình muốn add data từ file txt và lấy data đó ra với ạ from này thấy thích mà tịt quá .. mong có ai đó giúp
Anh Long ơi, em muốn hỏi chút. Trong khi code thì làm sao để mình tư duy được là nên tổ chức code như thế nào ạ. Ví dụ như trong bài này, làm sao để anh có thể tư duy được là sẽ khai báo và quản lý ChromeDriver trong class ProfileDetail, mà không phải là khai báo ở ngoài ạ. Em cảm ơn anh.
Anh Long cho em hỏi: Cái dòng này là sao em không hiểu anh? Anh có thể giải thích giúp em được không anh? Cảm ơn anh
Mong anh ra series Hook