Home Abstract Class and Async, should I make a new base class?
Reply: 0

Abstract Class and Async, should I make a new base class?

user2671
1#
user2671 Published in July 18, 2018, 4:54 am

I have a base class that I will be using to iterate though files and directories as shown here:

public abstract class FileRecursionBase
{
    protected DirectoryInfo Info;

    protected FileRecursionBase(string sourceDirectory, string targetDirectory)
    {
        SetSourceDirectory(sourceDirectory);
        TargetDirectory = targetDirectory;
    }

    private string _sourceDirectory;

    protected string GetSourceDirectory()
    {
        return _sourceDirectory;
    }

    protected void SetSourceDirectory(string value)
    {
        _sourceDirectory = value;
        Info =  new DirectoryInfo(value);
    }

    protected string TargetDirectory { get; set; }

    protected abstract void ProcessFile(FileInfo file);
    protected abstract void ProcessDirectory(DirectoryInfo directory);

    protected void EnumerateFiles()
    {
        foreach (var file in Info.EnumerateFiles())
        {
            ProcessFile(file);
        }
    }

    protected void EnumerateDirectories()
    {
        foreach (var directory in Info.EnumerateDirectories())
        {
            ProcessDirectory(directory);
        }
    }

    public virtual void Initialize()
    {
        EnumerateDirectories();
    }
}

And for simplicity let's make a simple counting class that implements this class

public class FileCounter : FileRecursionBase
{
    protected ICounter Counter;


    public FileCounter(string sourceDirectory, string targetDirectory, ICounter counter) : base(sourceDirectory, targetDirectory)
    {
        Counter = counter;
    }

    protected override void ProcessFile(FileInfo file)
    {
        Counter.Files++;
        Counter.FileSize += file.Length;
    }

    protected override void ProcessDirectory(DirectoryInfo directory)
    {
        SetSourceDirectory(directory.FullName);
        try
        {
            EnumerateFiles();
            EnumerateDirectories();
        }
        catch (Exception)
        {
            //ignore
        }
    }
}

The class works as intended and recursively enumerates based off the ProcessDirectory and ProcessFiles methods.

However, what can I do for cases where I wanted to ProcessFiles asynchronously? Since the abstract class is using protected methods, I cannot await a void on the Initialization.

Would I have to change the entire base class to use Tasks, even if the class has children that isn't asynchronous?

Or is the correct way is to just create a new base class that uses Tasks and copy and paste most of the code? Just seeing if anyone had ideas or if I am overlooking something.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.314414 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO