473,396 Members | 2,030 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

How to safely break the thread

Hi
i have Windows Form Class called Download.
Form Load event of this class raises new thread that starts downloading new
file via. www.
Problem is when i want to terminate the form.
I also need to break thread execution, and close all streams ( response
stream and file stream )
How to do this in professional way.
Many thanks
Jun 27 '06 #1
10 2494
It's really simple, thanks.
Jun 27 '06 #2
What about if i'll try to access for example Label attached to the form.

Your code:
void DownloadThreadProc(object obj)
{
byte[] buffer;
while ( !this.Disposing)
{
buffer = downloadFile(amountOfBytes);
storeDownloadedBytes(buffer);
//access label here
}
//cleanup actions here
//closing connection, freeing resource.
}
Problem is that i can check the flag, but the flag will not exist when the
form is already disposed.
Thus i cannot acces either flag, label.
In other words form might be disposed inside the while loop, and i will not
be able to access the flag.
PK
Jun 27 '06 #3
That is what i needed man
You really helped me
PK
Jun 27 '06 #4
Anyway. Is this normal that in such a code:
protected override void Dispose(bool disposing)
{
disposing = true;

if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);

downloadThread.Join();
}

i must wait about 30-40 sec on the Join method ?
My main part of the thread is :
while ((bufferCount = FileStream.Read(buffer, 0, 256)) > 0
&& !disposing)
{
store += bufferCount;
file.Write(buffer, 0, bufferCount);
}
where disposing is the flag you mentioned before.
Jun 27 '06 #5
Hello, PiotrKolodziej!

P> if (disposing && (components != null))
P> {
P> components.Dispose();
P> }
P> base.Dispose(disposing);

P> downloadThread.Join();
P> }

P> i must wait about 30-40 sec on the Join method ?

What happens during that time in the worker thread? Is FileStream.Read( ) executing fast?

--
Regards, Vadym Stetsyak
www: http://vadmyst.blogspot.com
Jun 27 '06 #6
I have set the brakepoint right after while loop in downloadThread, and when
i call Join() in Dispose() the breakpoint in downloadThread is nevere
reached.
I see it as a huge lag.
Jun 27 '06 #7
Vadim, .NET memmory model is not so clear, it's a bit bizarre :)
and using variable to check when break thread is not appropriate

Jon describe it in this article there
http://www.yoda.arachsys.com/csharp/...latility.shtml

I've posted ently in my blog http://spaces.msn.com/laflour in section
CodeSnippet how to break thread gracefully with description from IanG (have
no access to my blog now to specify direct link)

Hello, PiotrKolodziej!

P> Hi
P> i have Windows Form Class called Download.
P> Form Load event of this class raises new thread that starts downloading
P> new file via. www.
P> Problem is when i want to terminate the form.
P> I also need to break thread execution, and close all streams ( response
P> stream and file stream )
P> How to do this in professional way.

Thread that downloads file has to check the flag, that will indicate to abort to continue download.

pseudo code can look like this:
( The goal here is to let thread check that flag, that is why file is downloaded in portions )

void DownloadThreadProc(object obj)
{
byte[] buffer;
while ( !flagBreak )
{
buffer = downloadFile(amountOfBytes);
storeDownloadedBytes(buffer);
}
//cleanup actions here
//closing connection, freeing resource.
}

--
Regards, Vadym Stetsyak
www: http://vadmyst.blogspot


--
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do not
cease to be insipid." (c) Friedrich Nietzsche

Jun 27 '06 #8
Hello, Michael!

MN> Jon describe it in this article there
MN> http://www.yoda.arachsys.com/csharp/...latility.shtml

MN> I've posted ently in my blog http://spaces.msn.com/laflour in section
MN> CodeSnippet how to break thread gracefully with description from IanG
MN> (have no access to my blog now to specify direct link)

In the sample you provide, global var is used. Yes, I didn't mention that it has to be volatile in this case,
my miss.

However, volatilie will not suffice if value is larger then 4 bytes, suppose in 32-bit machine.

Then to avoid all the troubles Interlocked.CompareExchange can be used for flag testing, and Interlocked.Exchange can be used to set the flag.

--
Regards, Vadym Stetsyak
www: http://vadmyst.blogspot.com
Jun 27 '06 #9
Hello, PiotrKolodziej!

P> I have set the brakepoint right after while loop in downloadThread, and
P> when i call Join() in Dispose() the breakpoint in downloadThread is
P> nevere reached.
P> I see it as a huge lag.

Try, declaring that flag as static volatile bool as described in Michael's post

( http://laflour.spaces.msn.com/blog/cns!7575E2FFC19135B4!322.entry?_c11_blogpart_blogp art=blogview&_c=blogpart#permalink )

--
Regards, Vadym Stetsyak
www: http://vadmyst.blogspot.com
Jun 27 '06 #10
Try, declaring that flag as static volatile bool as described in Michael's
post

(
http://laflour.spaces.msn.com/blog/cns!7575E2FFC19135B4!322.entry?_c11_blogpart_blogp art=blogview&_c=blogpart#permalink )

I did exactly the same. When i use 2000 as parameter for Join() everything
is ok.
Problem is that without this Join never returns to caller thread.

Maybe you could shortly look at my thread. Maybe iam dooing some kind of
crical error:

private void downloadMethod()
{
long store = 0 ;
BinaryWriter file = null ;
Stream FileStream = null ;
byte[] buffer = new byte[256] ;
Int32 bufferCount = 0 ;

try
{
HttpWebRequest request = null;
HttpWebResponse response = null;

request = (HttpWebRequest)WebRequest.Create(FullPath);
request.Headers.Clear();
request.ProtocolVersion = HttpVersion.Version11;

response = (HttpWebResponse)request.GetResponse();

FileStream = response.GetResponseStream();
file = new BinaryWriter(File.Create(@"d:\\FM\\" +
fileName));

while ((bufferCount = FileStream.Read(buffer, 0, 256)) > 0
&& !disposing)
{
store += bufferCount;
file.Write(buffer, 0, bufferCount);
}

file.Close();
response.Close();

exitDelegate myDeleg = new exitDelegate(exitForm);
this.Invoke(myDeleg);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);

exitDelegate myDeleg = new exitDelegate(exitForm);
this.Invoke(myDeleg);
}
private void exitForm()
{
if (!disposing)
{
this.Dispose();
}
}
and the most important one:

protected override void Dispose(bool disposing)
{
disposing = true;

if (!downloadThread.Join(2000))
{
downloadThread.Interrupt();

downloadThread.Join();
}

if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
disposing is static and volatile like you said.
Would be really gratefull even for finding mistake ;)
PK
Jun 27 '06 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Russell E. Owen | last post by:
I've been doing some socket programming with threads and am confused how to safely shut down a connection. First of all, using the file-like object returned by urllib to do ftp file download...
0
by: 2G | last post by:
Hi I'm trying to safely stop a thread but as you might have guessed, I'm failing at it. GetCurrentThread seems to get the wrong handle, my form disappears when I try to stop the thread and it...
4
by: Frank Rizzo | last post by:
Hello, I want to use a variable as a signal to the thread that it should stop what it's doing (code below). As a rule, should I lock an object only when I am writing to it or do I have to lock...
14
by: iwinux | last post by:
Hi. Before I use scanf(), I must malloc the memory for it, like this: //Start char * buffer; buffer = malloc(20); scanf("%s", &buffer); //End
3
by: Jamie Risk | last post by:
I'm attempting to improve some serially executing code (that uses the SerialPort class) bogging Windows down when it runs. To do the 'antibogging' I'm following the example from MSDN...
3
by: =?Utf-8?B?c21rcmFtZXIwNzJmZGFzZmFzZGY=?= | last post by:
This questions is in reference to the article on Using Events in the C# Programmers Reference (http://msdn2.microsoft.com/en-us/library/ms173168.aspx). Under the Rasing Events section it says in...
12
by: Zytan | last post by:
Can I break the debugger into a worker thread? Right now, my app is freezing, and when I press pause, it stops on: Application.Run(new MyForm()); I don't know what that means. I know the...
15
by: suga.masanobu | last post by:
Hello group. I have thread in which I perform specific task in loop. I can specify, by check box, in what periods of time that task should be done, ex. instantly, with 5min break, with 15min...
17
by: byte8bits | last post by:
How does C++ safely open and read very large files? For example, say I have 1GB of physical memory and I open a 4GB file and attempt to read it like so: #include <iostream> #include <fstream>...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.