VB.NET - How to control, stop Thread pooling in visual basic 2005
Asked By Minhajul Shaoun
30-Sep-08 06:50 PM

Hello,
I am trying to send asynchronous web request and scrape the html content from the particular web page. I am using thread pool for easiest management of threading. Everything is working fine. There are 2 buttons. One for starting scraping and another for stop the process. How can i code stop button? I want to stop the process running whenever anyone press stop. Here is my code:
'Code begins
Private Sub ScanTimeoutCallback(ByVal State As Object, ByVal timedOut As Boolean)
If timedOut Then
Dim reqState As RequestState = CType(State, RequestState)
Dim HTTPData As DataObject
Dim sites As String = ""
If Not reqState Is Nothing Then
HTTPData = reqState.HTTPDataObj
reqState.RequestObj.Abort()
sites = reqState.sites
End If
End If
End Sub
'This is the thread pooling sub. I just call it like this - sendrequest(arrlist)
Public Sub SendRequest(ByVal uri As ArrayList)
For Each siteurl As String In uri
Dim httpdata As DataObject
httpdata = New DataObject
Dim Request As Net.HttpWebRequest = Net.HttpWebRequest.Create(siteurl)
Request.KeepAlive = True
Request.Method = "GET"
'ThreadPool.SetMaxThreads(1, 1)
'-- Asynchronously send the request
Dim State As New RequestState(httpdata, Request, siteurl)
Dim Result As IAsyncResult = CType(Request.BeginGetResponse(New AsyncCallback(AddressOf ReceiveResult), State), IAsyncResult)
ThreadPool.RegisterWaitForSingleObject(Result.AsyncWaitHandle, New WaitOrTimerCallback(AddressOf ScanTimeoutCallback), State, 18000000, True)
Next
End Sub
Private Sub ReceiveResult(ByVal Result As IAsyncResult)
'-- Asynchronously receive the response
Dim State As RequestState = CType(Result.AsyncState, RequestState)
Dim SR As IO.StreamReader
Dim Response As Net.HttpWebResponse
Dim Request As Net.HttpWebRequest = State.RequestObj
Try
Response = CType(Request.EndGetResponse(Result), Net.HttpWebResponse)
SR = New IO.StreamReader(Response.GetResponseStream()) '###
datastring = SR.ReadToEnd
datastring = extractemail(datastring)
dataurl = Request.Address.ToString
accesscontrol()
Catch WebEx As Net.WebException
datastring = "error occured"
dataurl = Request.Address.ToString
accesscontrol()
Finally
If Not Response Is Nothing Then
Response.Close()
End If
If Not SR Is Nothing Then
SR.Close()
End If
End Try
End Sub
Sub accesscontrol()
If Me.InvokeRequired Then
Me.Invoke(New MethodInvoker(AddressOf accesscontrol))
Else
'do something
End Sub
'Code ended
The whole process is working perfectly well. But how can i manage stop the process. I got the thread pooling code from the bromberg's article in eggheadcafe.com in c#. I just want to ask some guru whether my code is right or not. I want to make it more faster.
Regards...
There are two manner

1-
The Enter() and Exit() methods
The
Monitor class offers the Enter(object) and Exit(object) static methods. These methods
take an object as a parameter. This object constitutes a simple mean to uniquely identify the
resource which needs to be accessed in a synchronized way. When a thread calls the
Enter()
method, it waits to have the exclusive access right to the referenced object (it only waits if another
thread already has this right). Once this right has been acquired and consumed, the thread releases
this right by calling the
Exit() on this same object.
A thread can call
Enter() several times on the same object as long as it calls Exit()
as many times on the same object to release its exclusive access rights.
A thread can also own exclusive rights on several objects at the same time, but this can
lead to a deadlock situation.
You must never call the
Enter() and Exit() methods on an instance of a value type
such as an integer!
You must always call the
Exit() in a finally clause in order to free all exclusive
access rights no matter what happens.
If in Example 5‑5, a thread must raise
counter to its square while the other must multiply it by
two, we have to replace the use of the
Interlocked class by the use of the Monitor class. The code
for
f1() and f2() would then be:
Example 5‑6
using System.Threading;
class Program {
static long counter = 1;
static void Main() {
Thread t1 = new Thread( f1 );
Thread t2 = new Thread( f2 );
t1.Start(); t2.Start(); t1.Join(); t2.Join();
}
static void f1() {
for (int i = 0; i < 5; i++){
try{
Monitor.Enter( typeof( Program ) );
counter *= counter;
}
finally{ Monitor.Exit( typeof( Program ) ); }
System.Console.WriteLine(“counter^2 {0}”, counter);
Thread.Sleep(10);
}
}
static void f2() {
for (int i = 0; i < 5; i++){
try{
Monitor.Enter( typeof( Program ) );
counter *= 2;
}
finally{ Monitor.Exit( typeof( Program ) ); }
System.Console.WriteLine(“counter*2 {0}”, counter);
Thread.Sleep(10);
}
}
2-
The lock C# keyword
The C# language presents the
lock keyword which is an elegant alternative to using the Enter()
and
Exit() methods. Our program could then be rewritten like this:
Example
using System.Threading;
class Program {
static long counter = 1;
static void Main() {
Thread t1 = new Thread(f1);
Thread t2 = new Thread(f2);
t1.Start(); t2.Start(); t1.Join(); t2.Join();
}
static void f1() {
for (int i = 0; i < 5; i++){
lock( typeof(Program) ) { counter *= counter; }
System.Console.WriteLine(“counter^2 {0}”, counter);
Thread.Sleep(10);
}
}
static void f2() {
for (int i = 0; i < 5; i++){
lock( typeof(Program) ) { counter *= 2; }
System.Console.WriteLine(“counter*2 {0}”, counter);
Thread.Sleep(10);
}
}
}
As with
for and if, the blocks defined by the lock keyword are not required to use curly braces
if they only contain a single instruction. We could have written:
...
lock( typeof( Program ) )
counter *= counter;
...
The use of the
lock keyword provokes the creation by the C# compiler of a try/finally block
which allows you to anticipate any exception which might be raised. You can verify this by using
one of the
Reflector or ildasm.exe tool.
I guess it will be helpful for you
good lucks..
I am not talking about threading, but deeper of thread that is thread pooling
Hello Hamit,
Please see my code one more time. You gave an example using thread. But here i am talking about thread pooling. I can code the same thing with thread class. But that will be too hard as i am not multiplying. So, i need a solution for the stop button. Also i dont want to handle the computer resource myself. That is why i am using thread pooling not thread. Hope you understand.
Regards...
ok look IAsyncResult
class Program
{
public delegate int Deleg( int a, int b );
static int WriteSum( int a, int b )
{
Console.WriteLine( "Thread#{0}: Sum = {1}",
Thread.CurrentThread.ManagedThreadId , a+b);
return a + b;
}
static void SumDone( IAsyncResult async )
{
// Wait a second to simulate some work.
Thread.Sleep( 1000 );
Deleg proc = ( (AsyncResult) async ).AsyncDelegate as Deleg;
int sum = proc.EndInvoke( async );
Console.WriteLine( "Thread#{0}: Callback method sum = {1}",
Thread.CurrentThread.ManagedThreadId , sum );
( (
AutoResetEvent)async.AsyncState ).Set();
}
static void Main()
{
Deleg proc = WriteSum;
AutoResetEvent ev = new AutoResetEvent(false);
IAsyncResult async = proc.BeginInvoke( 10, 10, SumDone, ev );
Console.WriteLine(
"Thread#{0}: BeginInvoke() called! Wait for SumDone() completion.",
Thread.CurrentThread.ManagedThreadId );
ev.WaitOne();
Console.WriteLine(
"{0}: Bye... ", Thread.CurrentThread.ManagedThreadId );
}
}
How can i use thread.sleep?
Hello mate,
It is nice to get another reply from you. But you cant understand my problem. Can you show me how can i write thread.sleep(1000) in my thread pooling code? You cant. Because thread pooling does not support that. So, pls dont give me incorrect answer. Where is sir Pete or sir Robbe?
Yes I think I can Not Understand your query

class Program
{
private void ScanTimeoutCallback(object State, bool timedOut) {
if (timedOut) {
RequestState reqState = ((RequestState)(State));
DataObject HTTPData;
string sites = "";
if (!(reqState == null)) {
HTTPData = reqState.HTTPDataObj;
reqState.RequestObj.Abort();
sites = reqState.sites;
}
}
}
// This is the thread pooling sub. I just call it like this - sendrequest(arrlist)
public void SendRequest(ArrayList uri) {
foreach (string siteurl in uri) {
DataObject httpdata;
httpdata =
new DataObject();
Net.HttpWebRequest Request = Net.HttpWebRequest.Create(siteurl);
Request.KeepAlive =
true;
Request.Method =
"GET";
RequestState State =
new RequestState(httpdata, Request, siteurl);
IAsyncResult Result = ((IAsyncResult)(Request.BeginGetResponse(new AsyncCallback(new System.EventHandler(this.ReceiveResult)), State)));
ThreadPool.RegisterWaitForSingleObject(Result.AsyncWaitHandle, new WaitOrTimerCallback(new System.EventHandler(this.ScanTimeoutCallback)), State, 18000000, true);
}
}
private void ReceiveResult(IAsyncResult Result) {
// -- Asynchronously receive the response
RequestState State = ((RequestState)(Result.AsyncState));
IO.StreamReader SR;
Net.HttpWebResponse Response;
Net.HttpWebRequest Request = State.RequestObj;
try {
Response = ((Net.HttpWebResponse)(Request.EndGetResponse(Result)));
SR =
new IO.StreamReader(Response.GetResponseStream());
// ###
datastring = SR.ReadToEnd;
datastring = extractemail(datastring);
dataurl = Request.Address.ToString;
accesscontrol();
}
catch (Net.WebException WebEx) {
datastring =
"error occured";
dataurl = Request.Address.ToString;
accesscontrol();
}
finally {
if (!(Response == null)) {
Response.Close();
}
if (!(SR == null)) {
SR.Close();
}
}
}
void accesscontrol()
{
if (this.InvokeRequired) {
// yes I can not understand your query perfectly.
// just I think to write here a control sory if I faint again :)
this.Invoke(new MethodInvoker(new System.EventHandler(this.accesscontrol)));
}
else {
// do something
}
}
How to stop that process
How to stop the process when running through clicking stop button?
you need to kill the thread....
Hi,
for this you need to kill the thread on which the particular job is running... here the job is your web request and response processes....

Request) Dim Result As IAsyncResult = CType(Request.BeginGetResponse(New AsyncCallback(AddressOf ReceiveResult), State), IAsyncResult) ThreadPool.RegisterWaitForSingleObject(Result.AsyncWaitHandle, New WaitOrTimerCallback(AddressOf ScanTimeoutCallback), State, 60500, True) . . . End Sub Private Sub ReceiveResult(ByVal Result As IAsyncResult) '- - Asynchronously Dim State As RequestState = CType(Result.AsyncState, RequestState) Dim SR As StreamReader Dim Response As HttpWebResponse If Not State.HTTPDataObj.TimedOut Then Try Dim Request As HttpWebRequest = State.RequestObj State.HTTPDataObj.ResponseTimestamp = Logging.GetDateTimeStamp(False) Response = CType(Request.EndGetResponse(Result), HttpWebResponse) State.HTTPDataObj.ResponseCode = Response.StatusCode SR = New StreamReader(Response.GetResponseStream()) '### ERROR OCCURS HERE State.HTTPDataObj As WebException If Not WebEx.Response Is Nothing Then State.HTTPDataObj.ResponseCode = CType(WebEx.Response, HttpWebResponse).StatusCode SR = New StreamReader(CType(WebEx.Response, HttpWebResponse).GetResponseStream) State.HTTPDataObj.ResponseBody = SR.ReadToEnd() CType(WebEx.Response, HttpWebResponse).Close() Else State.HTTPDataObj.ResponseCode = "999" State.HTTPDataObj.ResponseBody = WebEx.Message End If Finally If ResponseTimestamp (1) State.HTTPDataObj.ResponseBody (1) State.HTTPDataObj.ResponseCode (1) State.HTTPDataObj.TimedOut (1) ThreadPool.RegisterWaitForSingleObject (1) HTTPData.TimedOut (1) RegisterWaitForSingleObject (1) Logging.GetDateTimeStamp (1) = A0 = A0 = A0 = A0 = A0 = A0
siteurl) Dim Result As IAsyncResult = CType(Request.BeginGetResponse(New AsyncCallback(AddressOf ReceiveResult), State), IAsyncResult) ThreadPool.RegisterWaitForSingleObject(Result.AsyncWaitHandle, New WaitOrTimerCallback(AddressOf ScanTimeoutCallback), State, 18000000, True) Next End Sub Private Sub ReceiveResult(ByVal Result As IAsyncResult As RequestState = CType(Result.AsyncState, RequestState) Dim SR As IO.StreamReader Dim Response As Net.HttpWebResponse Dim Request As Net.HttpWebRequest = State.RequestObj Try Response = CType(Request.EndGetResponse(Result), Net.HttpWebResponse) SR = New IO.StreamReader(Response.GetResponseStream()) '### datastring = SR.ReadToEnd datastring = extractemail(datastring) dataurl = Request.Address siteurl) ; IAsyncResult Result = ((IAsyncResult)(Request.BeginGetResponse( new AsyncCallback( new System.EventHandler( this .ReceiveResult)), State))) ; ThreadPool.RegisterWaitForSingleObject(Result.AsyncWaitHandle, new WaitOrTimerCallback( new System.EventHandler( this .ScanTimeoutCallback)), State, 18000000 , true ) ; } } private void ReceiveResult(IAsyncResult Result) { / / - - Asynchronously receive the response RequestState State = ((RequestState)(Result.AsyncState)) ; IO.StreamReader SR ; Net.HttpWebResponse Response ; Net.HttpWebRequest Request = State.RequestObj ; try { Response = ((Net.HttpWebResponse)(Request.EndGetResponse(Result))) ; SR = new IO.StreamReader(Response.GetResponseStream()) ; / / ### datastring = SR.ReadToEnd ; datastring = extractemail(datastring
app. • We use HttpWebRequest.BeginGetResponse() to initiate an asynchronous request. • We need to use ThreadPool.RegisterWaitForSingleObject() to register a timeout delegate for unresponsive Web requests. Asynchronous WebRequest calls ignore the WebRequest data, uriString); IAsyncResult result = request.BeginGetResponse( new AsyncCallback(UpdateItem), state); / / Register the timeout callback ThreadPool.RegisterWaitForSingleObject( result.AsyncWaitHandle, new WaitOrTimerCallback(ScanTimeoutCallback), state, (30* 1000), / / 30 second timeout true ); } } private static void UpdateItem (IAsyncResult result) { / / grab state object RequestState state = (RequestState)result.AsyncState; WebRequest request = (WebRequest)state.Request; / / get the Response HttpWebResponse response = (HttpWebResponse )request.EndGetResponse(result); Stream s = (Stream)response.GetResponseStream(); StreamReader readStream = new StreamReader( s ); / / dataString will new AsyncCallback(UpdateItem), state); We send the result object's AsyncWaitHandle into our ThreadPool's RegisterWaitForSingleObject method. The RegisterWaitForSingleObject method we use checks the current state of the specified object's WaitHandle. If the
gif / png / jpg) using below code HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http: / / localhost / company.gif"); HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); Stream receiveStream = httpWebResponse.GetResponseStream(); What exactly is missing here. . .can someone focus. . why I am not able to on my Web page ASP.NET Discussions Response.OutputStream.Write (1) Visual Studio 2008 (1) HttpWebResponse (1) HttpWebRequest (1) HttpWebResponse.GetResponseStream (1) Response.OutputStream (1) e What are you doing with receiveStream ? I dont know Response.ContentType = 3D "image / jpeg"; HttpWebRequest httpWebRequest = 3D (HttpWebRequest)WebRequest.Create("http: / / localhost / company.gif"); HttpWebResponse httpWebResponse = 3D (HttpWebResponse)httpWebRequest.GetResponse(); Stream receiveStream = 3D httpWebResponse.GetResponseStream(); int bufferSize = 3D 100; / / Size of