Skip to content

Commit 51773d2

Browse files
committed
Threading stuff
1 parent 8178ee7 commit 51773d2

File tree

5 files changed

+95
-40
lines changed

5 files changed

+95
-40
lines changed

SmartImage.Lib/SearchClient.cs

Lines changed: 42 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -43,9 +43,10 @@ public SearchClient(SearchConfig config)
4343
DetailedResults = new List<ImageResult>();
4444
ContinueTasks = new List<Task>();
4545

46-
m_w = new AutoResetEvent(false);
46+
DirectResultsWaitHandle = new AutoResetEvent(false);
4747

4848
Reload();
49+
4950
}
5051

5152
/// <summary>
@@ -96,8 +97,11 @@ public SearchClient(SearchConfig config)
9697

9798
public bool IsContinueComplete { get; private set; }
9899

99-
public List<Task<SearchResult>> Tasks { get; private set; }
100-
private List<Task> ContinueTasks { get; }
100+
public List<Task<SearchResult>> Tasks { get; private set; }
101+
102+
private List<Task> ContinueTasks { get; }
103+
104+
public WaitHandle DirectResultsWaitHandle { get; private set; }
101105

102106

103107
/// <summary>
@@ -127,10 +131,12 @@ public void Reset()
127131
FilteredResults.Clear();
128132
DetailedResults.Clear();
129133
ContinueTasks.Clear();
130-
PendingCount = 0;
134+
PendingCount = 0;
135+
131136
IsComplete = false;
132137
IsContinueComplete = false;
133-
m_w = new AutoResetEvent(false);
138+
139+
DirectResultsWaitHandle = new AutoResetEvent(false);
134140

135141
Reload();
136142
}
@@ -243,6 +249,12 @@ public async Task RunContinueAsync(CancellationToken? c = null)
243249

244250
ContinueTasks.Remove(task);
245251
IsContinueComplete = !ContinueTasks.Any();
252+
253+
254+
}
255+
256+
if (!DirectResultsWaitHandle.SafeWaitHandle.IsInvalid||!DirectResultsWaitHandle.SafeWaitHandle.IsClosed) {
257+
((AutoResetEvent) DirectResultsWaitHandle).Set();
246258
}
247259
}
248260

@@ -251,37 +263,36 @@ private void GetResultContinueCallback(Task<SearchResult> task, object state)
251263
{
252264
var value = task.Result;
253265

254-
if (value.IsSuccessful && value.IsNonPrimitive) {
255-
266+
if (!value.IsSuccessful || !value.IsNonPrimitive || value.Scanned) {
267+
return;
268+
}
256269

257-
if (!value.Scanned) {
258-
// var task2 = value.FindDirectResultsAsync();
259-
// task2.Wait();
260-
// var result = task2.Result;
270+
// var task2 = value.FindDirectResultsAsync();
271+
// task2.Wait();
272+
// var result = task2.Result;
261273

262-
var result = value.FindDirectResultsAsync();
274+
var result = value.FindDirectResultsAsync();
263275

264-
if (result.Any()) {
265-
result = result /*.Where(x => x.Direct != null)*/
266-
.ToList();
276+
if (result.Any()) {
277+
result = result /*.Where(x => x.Direct != null)*/
278+
.ToList();
267279

268-
DirectResults.AddRange(result);
280+
DirectResults.AddRange(result);
269281

270-
var autoResetEvent = ((AutoResetEvent) m_w);
282+
value.Scanned = true;
283+
var autoResetEvent = ((AutoResetEvent)DirectResultsWaitHandle);
284+
271285

272-
if (DirectResults.Count > 0 && !autoResetEvent.SafeWaitHandle.IsClosed) {
273-
Debug.WriteLine("wait handle set");
274-
autoResetEvent.Set();
286+
if (DirectResults.Count > 0&&!DirectResultsWaitHandle.SafeWaitHandle.IsClosed /*|| ContinueTasks.Count==1*/) {
287+
Debug.WriteLine("wait handle set");
288+
autoResetEvent.Set();
289+
}
275290

276-
}
291+
DirectResultCompleted?.Invoke(null, EventArgs.Empty);
277292

278-
value.Scanned = true;
293+
// if (result.Any()) { }
279294

280-
ResultUpdated?.Invoke(null, EventArgs.Empty);
281295

282-
// if (result.Any()) { }
283-
}
284-
}
285296
}
286297
}
287298

@@ -358,7 +369,7 @@ public static BaseSearchEngine[] GetAllSearchEngines()
358369
/// <summary>
359370
/// Fires when a result has been updated with new information
360371
/// </summary>
361-
public event EventHandler ResultUpdated;
372+
public event EventHandler DirectResultCompleted;
362373

363374
/// <summary>
364375
/// Fires when a result is returned (<see cref="RunSearchAsync" />).
@@ -375,8 +386,6 @@ public static BaseSearchEngine[] GetAllSearchEngines()
375386

376387
private static readonly SmartImageException SearchException = new("Search must be completed");
377388

378-
public WaitHandle m_w;
379-
380389

381390
public void Dispose()
382391
{
@@ -388,6 +397,10 @@ public void Dispose()
388397
result.Dispose();
389398
}
390399

400+
if (!DirectResultsWaitHandle.SafeWaitHandle.IsClosed) {
401+
DirectResultsWaitHandle.Dispose();
402+
403+
}
391404
}
392405
}
393406

SmartImage.Lib/Searching/SearchResult.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -148,16 +148,16 @@ public List<ImageResult> FindDirectResultsAsync()
148148
Debug.WriteLine($"searching within {Engine.Name}");
149149

150150
var directResults = new List<ImageResult>();
151-
152-
var ll=Parallel.For(0, AllResults.Count, (i, pls) =>
151+
152+
var ll = Parallel.For(0, AllResults.Count, (i, pls) =>
153153
{
154154
var allResult = AllResults[i];
155155

156156
var task = allResult.ScanForImagesAsync();
157157
task.Wait();
158158
var b = task.Result;
159159

160-
if (b && !directResults.Contains(allResult)&& allResult.Direct != null) {
160+
if (b && !directResults.Contains(allResult) && allResult.Direct != null) {
161161
Debug.WriteLine($"{nameof(SearchResult)}: Found direct result {allResult.Direct.Url}");
162162

163163
directResults.Add(allResult);

SmartImage.Lib/Utilities/ImageHelper.cs

Lines changed: 47 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,12 @@
1212
using System.Threading.Tasks;
1313
using AngleSharp.Html.Dom;
1414
using AngleSharp.Html.Parser;
15+
using Flurl.Http;
1516
using JetBrains.Annotations;
1617
using Kantan.Net;
1718
using Novus.OS;
1819
using static Kantan.Diagnostics.LogCategories;
20+
using HttpRequestMessage = System.Net.Http.HttpRequestMessage;
1921

2022
#pragma warning disable CS0168
2123
#pragma warning disable IDE0059
@@ -138,12 +140,54 @@ public static Task<List<DirectImage>> ScanForImages(string url, int count = 10,
138140

139141
public static bool IsImage(string url, out DirectImage di, int timeout = TimeoutMS, CancellationToken? token = null)
140142
{
143+
const string svg_xml = "image/svg+xml";
144+
const string image = "image";
145+
const int min_size_b = 50_000;
141146
di = new DirectImage();
142147

143148
if (!UriUtilities.IsUri(url, out Uri u)) {
144149
return false;
145150
}
146151

152+
// var task = url.GetAsync();
153+
// task.Wait();
154+
/*try {
155+
var task = new HttpRequestMessage( HttpMethod.Get, url);
156+
var cc =new HttpClient(){};
157+
158+
var rg1 =cc.Send(task);
159+
// var rg1 = task.Result;
160+
if (!rg1.IsSuccessStatusCode) {
161+
return false;
162+
}
163+
// var contentType = rg1.ResponseMessage.Content.Headers.ContentType.MediaType;
164+
var contentType = rg1.Content.Headers.ContentType.MediaType;
165+
166+
if (contentType.ToString().StartsWith(image) && contentType != svg_xml) {
167+
return true;
168+
}
169+
170+
var rrr = rg1.Content.ReadAsByteArrayAsync();
171+
172+
// var rrr=rg1.ResponseMessage.Content.ReadAsByteArrayAsync();
173+
rrr.Wait();
174+
var rgx1 = rrr.Result;
175+
176+
var data = MediaTypes.ResolveFromData(rgx1);
177+
178+
if (data.StartsWith(image)&&data!=svg_xml) {
179+
return true;
180+
}
181+
}
182+
catch (Exception e) {
183+
Debug.WriteLine($"{e.Message}");
184+
}*/
185+
186+
/*
187+
*
188+
*/
189+
190+
147191
var responseTask = HttpUtilities.GetHttpResponseAsync(url, timeout, HttpMethod.Head, token: token);
148192
responseTask.Wait();
149193
var response = responseTask.Result;
@@ -169,14 +213,13 @@ public static bool IsImage(string url, out DirectImage di, int timeout = Timeout
169213
// The content-type returned from the response may not be the actual content-type, so
170214
// we'll resolve it using binary data instead to be sure
171215

172-
const string svg_xml = "image/svg+xml";
173-
const string image = "image";
174-
const int min_size_b = 50_000;
216+
175217

176218
var length = response.Content.Headers.ContentLength;
177219
di.Response = response;
220+
221+
178222
string mediaType;
179-
180223
try {
181224
mediaType = ResolveMediaTypeFromData(url, token);
182225
}

SmartImage/Program.cs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -213,7 +213,7 @@ private static async Task Main(string[] args)
213213

214214
Client.ResultCompleted += OnResultCompleted;
215215
Client.SearchCompleted += OnSearchCompleted;
216-
Client.ResultUpdated += OnResultUpdated;
216+
Client.DirectResultCompleted += OnDirectResultCompleted;
217217

218218
Console.CancelKeyPress += OnCancel;
219219

@@ -243,7 +243,6 @@ private static async Task Main(string[] args)
243243
/*Client.Dispose();
244244
Client.Reset();
245245
*/
246-
247246
}
248247

249248

@@ -259,7 +258,7 @@ private static void OnCancel(object sender, ConsoleCancelEventArgs eventArgs)
259258
SystemSounds.Hand.Play();
260259
}
261260

262-
private static void OnResultUpdated(object sender, EventArgs result)
261+
private static void OnDirectResultCompleted(object sender, EventArgs result)
263262
{
264263
ResultDialog.Refresh();
265264
}

SmartImage/UI/AppToast.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ internal static void ShowToast(object sender, SearchCompletedEventArgs args)
6464
if (Program.Config.NotificationImage) {
6565

6666

67-
var w = Program.Client.m_w;
67+
var w = Program.Client.DirectResultsWaitHandle;
6868
w.WaitOne();
6969
w.Dispose();
7070

0 commit comments

Comments
 (0)