Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6008721
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T01:51:53+00:00 2026-05-23T01:51:53+00:00

I’ve got a Stream object and I am using BeginRead to begin reading (obviously)

  • 0

I’ve got a Stream object and I am using BeginRead to begin reading (obviously) into a buffer; the AsyncCallback function is called once the reading is complete. Within this function I can check if the user wants to get the next ‘block’ and start the BeginRead process again.

The problem I have is the user may choose to cancel while the stream is still reading (so before the AsyncCallback function is called), so how can I cancel the reading of the stream?

Just to further explain the issue – it seems I would have the same outcome if I use a BackgroundWorker with the Streams Read method or the asynchronous BeginRead method. The user could be left waiting for any length of time for the Read/BeginRead method to complete before I can check if the stream should stop reading.

Edit: The code below should do the job, I’m a million miles away from being anything decent in C# so it may well have a couple of bugs as I doubt it’s perfect, although it does demonstrate the solution.

In brief, the CWorkManager manages a certain number of threads (which are held within a CWorkerDetail class). Each CWorkerDetail has a status, which can be EWaiting meaning the worker can be started, EReading which means the worker is reading from a source, during which time the worker can be stopped instantly, EWriting which saves the data that was read to the disk – this cannot be stoppped instantly and this process must complete before the thread is stopped. Finally there is EAborting which is set by the manager if the worker should be aborted as soon as possible; right now this is only set if the worker is in the middle of something which cannot be interrupted (such as writing to disk).

Right now, there isn’t actually any reading or writing going on, as that would just complicate the main solution (which is basically just the StopWorker function checking a flag of CWorker to see if it can abort instantly); as such we simply cause the thread to sleep.

The GUI side is fairly simple with just a listbox (which shows the status of each worker) and a stop and start button. All code is below, hope this helps somebody, but as I say I’m not brilliant with C# so please watch out for bugs etc…

CWorkManager.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;


namespace ThreadApplication {


    //A worker that spawns a number of threads (managed internally) that does nothing useful at all.
    public class CWorkManager {


        //The status of the worker.
        public enum EWorkerStatus {
            EWaiting,
            EReading,
            EWriting,
            EAborting,
        }


        //Holds all data relevant to the worker.
        private class CWorkerDetails {

            //Simple variables.
            private readonly Object _Lock=new Object();
            private Thread gThread;
            private EWorkerStatus gStatus;
            private CWorkManager gParentInstance;
            private int gIndex;

            //Simple constructor.
            public CWorkerDetails(int aIndex, CWorkManager aParentInstance, Thread aThread, EWorkerStatus aStatus) {
                gIndex=aIndex;
                gParentInstance=aParentInstance;
                gThread=aThread;
                gStatus=aStatus;
            }

            //Simple get set methods.
            public Thread GetThread() { lock(_Lock) { return gThread; } }
            public EWorkerStatus GetStatus() { lock(_Lock) { return gStatus; } }

            //Sets the status and automatically updates the GUI.
            public void SetStatus(EWorkerStatus aStatus) {
                lock(_Lock) {
                    gStatus=aStatus;
                    Form1.gInstance.Invoke(new UpdateGUIDelegate(gParentInstance.UpdateGUI), new object[] { gIndex, GetStatus() });
                }
            }

        }


        //Worker variable.
        private List<CWorkerDetails> gWorkers;


        //Simple constructor.
        public CWorkManager(int aWorkerCount){
            gWorkers=new List<CWorkerDetails>();
            for(int tIndex=0; tIndex<aWorkerCount; tIndex++)
                gWorkers.Add(null);
        }


        //Creates and starts the worker.
        public void StartWorker(int aWorkerIndex) {

            //Create a new worker if there is none or if it is waiting to start.
            if(gWorkers.ElementAt(aWorkerIndex)==null||gWorkers.ElementAt(aWorkerIndex).GetStatus()==EWorkerStatus.EWaiting)
                gWorkers[aWorkerIndex]=new CWorkerDetails(aWorkerIndex, this, new Thread(new ParameterizedThreadStart(WorkerMethod)), EWorkerStatus.EWaiting);

            //If the worker is waiting to start, then start.
            if(gWorkers.ElementAt(aWorkerIndex).GetStatus()==EWorkerStatus.EWaiting)
                gWorkers.ElementAt(aWorkerIndex).GetThread().Start(gWorkers.ElementAt(aWorkerIndex));
        }


        //Stops the worker.
        public void StopWorker(int aWorkerIndex) {

            //Do nothing if the worker is null.
            if(gWorkers.ElementAt(aWorkerIndex)==null)
                return;

            //Do nothing if the worker is waiting.
            if(gWorkers.ElementAt(aWorkerIndex).GetStatus()==EWorkerStatus.EWaiting)
                return;

            //If the worker is reading we can abort instantly.
            if(gWorkers[aWorkerIndex].GetStatus()==EWorkerStatus.EReading) {
                gWorkers[aWorkerIndex].GetThread().Abort();
                gWorkers[aWorkerIndex].SetStatus(EWorkerStatus.EWaiting);
                return;
            }

            //Since the worker is not reading or waiting, we have to request the 
            //worker to abort by itself.
            gWorkers[aWorkerIndex].SetStatus(EWorkerStatus.EAborting);

        }


        //Updates the GUI.
        private delegate void UpdateGUIDelegate(int aIndex, EWorkerStatus aStatus);
        private void UpdateGUI(int aIndex, EWorkerStatus aStatus) {
            Form1.gInstance.SetThreadStatus(aIndex, aStatus);
        }


        //This method is where all the real work happens.
        private void WorkerMethod(Object aWorker) {

            //Fetch worker.
            CWorkerDetails mWorker=(CWorkerDetails)aWorker;

            //Loop forever, the thread will exit itself when required.
            while(true) {

                //Is the worker status aborting - if so we stop here.
                if(mWorker.GetStatus()==EWorkerStatus.EAborting) {
                    mWorker.SetStatus(EWorkerStatus.EWaiting);
                    return;
                }

                //This would normally be reading from a stream which would cause the thread
                //to block, simulate this by just sleeping the thread.
                mWorker.SetStatus(EWorkerStatus.EReading);
                Thread.Sleep(3000);

                //Is the worker status aborting - if so we stop here.
                if(mWorker.GetStatus()==EWorkerStatus.EAborting) {
                    mWorker.SetStatus(EWorkerStatus.EWaiting);
                    return;
                }

                //All data has been read, set status to writing and again simulate by
                //sleeping the thread.
                mWorker.SetStatus(EWorkerStatus.EWriting);
                Thread.Sleep(3000);

            }

        }

    }


}

Form1.cs:


Contains:

  • A List box (ListBox_WorkerStatus)
  • A button (Button_Start)
  • A button (Button_Stop)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;


namespace ThreadApplication {


    public partial class Form1:Form {


        public static Form1 gInstance;
        private CWorkManager gManager;


        public Form1() {
            InitializeComponent();
            Button_Start.Click+=new EventHandler(Button_Start_Click);
            Button_Stop.Click+=new EventHandler(Button_Stop_Click);
            gInstance=this;
            for(int tIndex=0; tIndex<5; tIndex++)
                ListBox_WorkerStatus.Items.Add("Created");
            gManager=new CWorkManager(ListBox_WorkerStatus.Items.Count);
        }


        public void SetThreadStatus(int aIndex, CWorkManager.EWorkerStatus aStatus) {
            ListBox_WorkerStatus.Items[aIndex]=aStatus.ToString();
        }


        private void Button_Start_Click(object sender, EventArgs e) {
            if(ListBox_WorkerStatus.SelectedIndex>=0) {
                gManager.StartWorker(ListBox_WorkerStatus.SelectedIndex);
            }
        }


        private void Button_Stop_Click(object sender, EventArgs e) {
            if(ListBox_WorkerStatus.SelectedIndex>=0) {
                gManager.StopWorker(ListBox_WorkerStatus.SelectedIndex);
            }
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e) {
            for(int tIndex=0; tIndex<ListBox_WorkerStatus.Items.Count; tIndex++) {
                gManager.StopWorker(tIndex);
            }
        }


    }


}

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T01:51:54+00:00Added an answer on May 23, 2026 at 1:51 am

    Use BackgroundWorker

    BackgroundWorker backgroundWorker1= new backgroundWorker()
    
    private void InitializeBackgroundWorker()
    {
            backgroundWorker1.DoWork += 
                new DoWorkEventHandler(backgroundWorker1_DoWork);
    
            backgroundWorker1.WorkerSupportsCancellation = true;
    }
    
    
    
    private void backgroundWorker1_DoWork(object sender, 
            DoWorkEventArgs e)
    {   
            BackgroundWorker worker = sender as BackgroundWorker;
    
            e.Result = YourWorkToDo();
    }
    
    public void Start()
    {
        backgroundWorker1.RunWorkerAsync()
    }
    
    public voic Cancel()
    {
        backgroundWorker1.CancelAsync();
    {
    

    If you want more help leave comment

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

i got an object with contents of html markup in it, for example: string
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I've got a string that has curly quotes in it. I'd like to replace
this is what i have right now Drawing an RSS feed into the php,
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
We're building an app, our first using Rails 3, and we're having to build
I'm making a simple page using Google Maps API 3. My first. One marker
I have just tried to save a simple *.rtf file with some websites and
I want to count how many characters a certain string has in PHP, but
I have a JSP page retrieving data and when single or double quotes are

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.