Всем привет!!! пытаюсь написать программу которая собирает все ссылки с сайта и информацию об этих ссылках(ну типа Ок или error)( и всё время хранить информацию о количестве обработыанных ссылок) вот нужно всё это сделать используя . Async await. Lock-free программирование. и потокобезопасные коллекции я вот кое что сделал, но совсем не уверен что правильно а когда попытался добавить interlocked то всё поорушилось.... и да я совсем не понимаю как мне отловить что всё уже отработано ?
вот код
C# |
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
| 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;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Threading;
using System.Collections.Concurrent;
using System.Text.RegularExpressions;
using System.Web;
using System.Net;
namespace firstAttempt11Laba
{
public partial class Form1 : Form
{
static ConcurrentQueue<String> m_queue = new ConcurrentQueue<string>();
static Queue<string> m_urls = new Queue<string>();
static int m_countAllLinks = 0;
static int m_linkhandled = 0;
static int m_badLinks = 0;
static int m_correctLink = 0;
private static string rootUrl;
static ConcurrentDictionary<string, System.Net.HttpStatusCode> m_dictionary = new ConcurrentDictionary<string, System.Net.HttpStatusCode>();
async static void DownloadWebPage(string url, string siteUrl)
{
try
{
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(url)) // тут запускается второй поток, а главный поток возвращается туда где был вызов метода DownloadWebPage
using (HttpContent content = response.Content) /// тут уже работает второй поток
{
if (!m_dictionary.ContainsKey(url))/// тут уже работает второй поток
{
while (!m_dictionary.TryAdd(url, response.StatusCode))/// тут уже работает второй поток
{
;/// тут уже работает второй поток
}/// тут уже работает второй поток
string result = await content.ReadAsStringAsync(); // выплняется в 3 потоке
DumpHRefs(result, siteUrl); // выполняется в 3 потоке
}
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
public static string ToAbsoluteUrl(string relativeUrl)
{
string res = rootUrl;
if (relativeUrl.StartsWith("/"))
{
for (int i = 1; i < relativeUrl.Count(); ++i)
{
res += relativeUrl[i];
}
}
return res;
}
private static void DumpHRefs(string inputString, string rootUrl)
{
Match m;
Queue<String> foundUrls = new Queue<String>();
string HRefPattern = "href\\s*=\\s*(?:[\"'](?<1>[^\"']*)[\"']|(?<1>\\S+))";
try
{
m = Regex.Match(inputString, HRefPattern,
RegexOptions.IgnoreCase | RegexOptions.Compiled,
TimeSpan.FromSeconds(1));
while (m.Success)
{
String siteUrl = ToAbsoluteUrl(m.Groups[1].ToString());
if (!siteUrl.Contains(rootUrl))
{
m = m.NextMatch();
continue;
}
if (!m_dictionary.ContainsKey(siteUrl))
{
foundUrls.Enqueue(siteUrl);
}
m = m.NextMatch();
}
}
catch (RegexMatchTimeoutException)
{
MessageBox.Show("The matching operation timed out.");
}
foreach (String site in foundUrls)
{
try
{
DownloadWebPage(site, rootUrl);
}
catch (InvalidOperationException e)
{
MessageBox.Show(e.Message);
}
}
}
public Form1()
{
InitializeComponent();
}
private void traverseUrl(string url)
{
try
{
DownloadWebPage(url, rootUrl);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
string siteUrl = textBox1.Text.Trim();
rootUrl = siteUrl;
if (siteUrl == "")
{
MessageBox.Show("Вы не ввели адрес страницы!!!");
}
traverseUrl(siteUrl);
}
private void button2_Click(object sender, EventArgs e)
{
this.dataGridView1.DataSource = null;
this.dataGridView1.Rows.Clear();
int i = 0;
foreach (var s in m_dictionary)
{
DataGridViewRow row = (DataGridViewRow)dataGridView1.Rows[0].Clone();
row.Cells[0].Value = s.Key;
row.Cells[1].Value = s.Value;
this.dataGridView1.Rows.Add(row); // добавление строк
}
}
}
} |
|
Всем спасибо за внимание и за помощь!!!