Click here to Skip to main content
15,892,809 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
My application have thread which get started on start button click and do file copy operation.
OnCancel button click causes thread to stop the processing and delete copied file.
how Can I achieve this?
Posted

You can rewrite your code with little logic:

Read the file in small chunks and write it out to the destination. Periodically check whether you've been asked to cancel and if you detect that, stop writing and close the files.
 
Share this answer
 
For the above logic, the code sample is attached here:

C#
void CopyStream(Stream inputStream, Stream outputStream)
{
    var buffer = new byte[1024];

    int bytesRead;
    while((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0)
    {
        outputStream.Write(buffer, 0, bytesRead);
        if(cancelled){
           // cleanup

           return;
        }
    }
}
 
Share this answer
 
Comments
VICK 18-May-15 5:15am    
It would be nice and better to Edit your first solution and update with what you have added in Solution 2.. rather than posting multiple solution.s :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900