私はまだこのスレッディングに夢中です。私は50000のURLを持っていると言うと、10個のURLをまとめて処理するように、これらのURLの内容を同時に取得したいとします。これらのURLの1つが処理を終了すると、リスト内のすべてのURLの処理が終了するまで、キューリストから別の1が追加されます。今どのように私はC#のと...ここで私はすべてのアイデアをいただければ幸いです:)C#のスレッドプールにキュータスクを追加する方法
よろしくこれまで..
class RequestState
{
public WebRequest Request;
// holds the request
public object Data;
// store any data in this
public string SiteUrl;
// holds the UrlString to match up results (Database lookup, etc).
public RequestState(WebRequest request, object data, string siteUrl)
{
this.Request = request;
this.Data = data;
this.SiteUrl = siteUrl;
}
}
private void PROCESS_URLS_Click(object sender, EventArgs e)
{
//run the process
process_URLs();
}
private int ThreadsCount = 0;
private void process_URLs()
{
//count threads number
ThreadsCount = URLS_LISTVIEW.SelectedItems.Count;
//loop through all URLs in listview
for (int i = 0; i < URLS_LISTVIEW.SelectedItems.Count; i++)
{
try
{
//get url string
string myURLs = URLS_LISTVIEW.SelectedItems[i].SubItems[0].Text.Trim();
// for each URL in the collection...
WebRequest request = HttpWebRequest.Create(myURLs);
request.Method = "GET";
object data = new object();
RequestState state = new RequestState(request, data, myURLs);
IAsyncResult result = request.BeginGetResponse(new AsyncCallback(UpdateItem), state);
ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, new WaitOrTimerCallback(ScanTimeoutCallback), state, (30 * 1000), true);
}
catch (ThreadStateException es)
{
MessageBox.Show(es.Message);
}
}
}
private void UpdateItem(IAsyncResult result)
{
RequestState state = (RequestState)result.AsyncState;
WebRequest request = (WebRequest)state.Request;
try
{// grab the custom state object
// get the Response
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
// process the response...
Stream s = (Stream)response.GetResponseStream();
StreamReader readStream = new StreamReader(s);
//data grabbed
string dataString = readStream.ReadToEnd();
response.Close();
s.Close();
readStream.Close();
//finished grabbing content for this thread.
ThreadsCount = ThreadsCount - 1;
//if all threads finished running then execute final code to tell the user the process finished
if (ThreadsCount < 1)
{
//show message
MessageBox.Show("finished");
}
// Thread.Sleep(400);
}
private static void ScanTimeoutCallback(object state, bool timedOut)
{
if (timedOut)
{
RequestState reqState = (RequestState)state;
if (reqState != null)
reqState.Request.Abort();
}
}
をやっているコードがあることを行うことができ、
これは、最初からすべてを書いておく必要があることを意味しますか? – SolidSnake
あなたは 'WebRequest'などのように実際に* URLを処理するコードを再利用することができますが、個人的には' WebClient'を使ってそれを単純化します。長期的な利点を考えてみましょう - 維持するコードはずっと少なくて済みます。 – BrokenGlass
サンプルを表示できますか?私はここで本当に失われています.. :( – SolidSnake