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

  • SEARCH
  • Home
  • 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 8937205
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T10:22:05+00:00 2026-06-15T10:22:05+00:00

I have this base class structure: Base: public abstract class BackgroundTask { protected readonly

  • 0

I have this base class structure:
Base:

public abstract class BackgroundTask
{
    protected readonly Logger Logger = LogManager.GetCurrentClassLogger();

    protected virtual void Initialize()
    {
        // initialize database access
    }

    public void Run()
    {
        Initialize();
        try
        {
            Execute();
            // insert to database or whatever
        }
        catch (Exception ex)
        {
            Logger.ErrorException(string.Format("Error proccesing task: {0}\r\n", ToString()), ex);
            Exceptions.Add(ex);
        }
        finally
        {
            TaskExecuter.Discard();
        }
    }

    protected abstract void Execute();
    public abstract override string ToString();
    public IList<Exception> Exceptions = new List<Exception>();
}

Task executor:

public static class TaskExecuter
{
    private static readonly ThreadLocal<IList<BackgroundTask>> TasksToExecute
        = new ThreadLocal<IList<BackgroundTask>>(() => new List<BackgroundTask>());

    public static void ExecuteLater(BackgroundTask task)
    {
        TasksToExecute.Value.Add(task);
    }

    public static void StartExecuting()
    {
        foreach (var backgroundTask in TasksToExecute.Value)
        {
            Task.Factory.StartNew(backgroundTask.Run);
        }
    }

    public static void Discard()
    {
        TasksToExecute.Value.Clear();
        TasksToExecute.Dispose();
    }
}

FileTask:

public class FileTask : BackgroundTask
{
    protected static string BaseFolder = @"C:\ASCII\";
    private static readonly ReaderWriterLockSlim Lock = new ReaderWriterLockSlim();
    private readonly string _folder;

    private IHistoryRepository _historyRepository;

    public string Folder
    {
        get { return _folder; }
    }

    public FileTask(string folder)
    {
        _folder = string.Format("{0}{1}", BaseFolder, folder);
    }

    protected override void Initialize()
    {
        _historyRepository = new HistoryRepository();
    }

    protected override void Execute()
    {
        // todo: Get institute that are active,
        var institute = MockInstitute(); // todo: uncomment _historyRepository.FindInstituteByFolderName(Folder);

        // todo: Update institute, lastupdate - [date] | [files amount] | [phonenumbers amount]
        if (institute == null)
        {
            Logger.Warn("Not found data", Folder);
            return;
        }

        // todo: read file get encoding | type and parse it
        Task.Factory.StartNew(ReadFile);
    }

    private void ReadFile()
    {
        var list = GetFilesByFolder();
        StreamReader sr = null;
        try
        {
            Lock.EnterReadLock();
            foreach (var fi in list)
            {
                var fileName = fi.FullName;
                Logger.Info("Line: {0}:=> Content: {1}", fileName, Thread.CurrentThread.ManagedThreadId);
                sr = new StreamReader(fileName, DetectEncoding(fileName));
                string currentLine;
                while ((currentLine = sr.ReadLine()).ReturnSuccess())
                {
                    if (string.IsNullOrEmpty(currentLine)) continue;
                    Logger.Info("Line: {0}:=> Content: {1}", fileName, currentLine);
                }
            }
            Lock.ExitReadLock();
        }
        finally
        {
            if (sr != null) sr.Dispose();
            Logger.Info("Finished working" + Folder);
        }
    }

    protected IEnumerable<FileInfo> GetFilesByFolder()
    {
        return Directory.GetFiles(Folder).Select(fileName => new FileInfo(fileName));
    }

    protected Encoding DetectEncoding(string file)
    {
        using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
        {
            var cdet = new Ude.CharsetDetector();
            cdet.Feed(fs);
            cdet.DataEnd();
            return cdet.With(x => x.Charset)
                       .Return(x => Encoding.GetEncoding(cdet.Charset),
                                    Encoding.GetEncoding("windows-1255"));
        }
    }

    private Institute MockInstitute()
    {
        return new Institute
        {
            FromFolderLocation = string.Format("{0}{1}", BaseFolder, Folder)
        };
    }

    public override string ToString()
    {
        return string.Format("Folder: {0}", Folder);
    }
}

When don’t read the file every thing ok, the Log is populated and every thing runs smooth,
but when i attach the Task.Factory.StartNew(ReadFile); method i have an exception.

Exception:

Cannot access a disposed object.
Object name: 'The ThreadLocal object has been disposed.'.

How do i solve that issue? might i need to change the LocalThread logic, or what – i have been trying to handle that issue, for almost a day.

BTW: It’s an MVC4 project, and C# 5.0 and i’m trying to TDD it all.

  • 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-06-15T10:22:06+00:00Added an answer on June 15, 2026 at 10:22 am

    You shouldn’t be calling TasksToExecute.Dispose();
    there.

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

Sidebar

Related Questions

I have a follwing class structure: public abstract class AbstractFoo { public virtual void
I have this code in base class protected virtual bool HasAnyStuff<TObject>(TObject obj) where TObject:class
I have this code structure: public abstract class ContentEntryBase { public string UniqueIdentifier; public
I have a base class like this: public class BaseResponse { public string ErrorMessage
Consider the following class structure: public class Foo<T> { public virtual void DoSomething() {
I have a class like this: [Serializable] public class Structure { #region Constants and
I have next structure: @Component public abstract class HuginJob extends QuartzJobBean {...} @Component(CisxJob) public
Given the following class structure: class Base { virtual void outputMessage() { cout <<
a question about class design. Currently I have the following structure: abstract Base Repository
I have a custom WPF control base class. This base class registers a custom

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.