Home > Blockchain >  Load byte[] Property of Class Only When Needed
Load byte[] Property of Class Only When Needed

Time:12-17

I have a class that returns a List that is bound to a grid. One of my property is a byte[] array that should only be populated if someone double clicks on the cell in the grid cell with the file. At that point, the file should be downloaded an presented to the user. Just an event with a file name and Process.Start(...

Because I'm binding the list to the grid, it is calling the "File" property and filling the value giving it an eager type behavior rather than the lazy behavior I am looking for.

Is there any way I can stop this property from filling in the data class (below) without having to modify a UI level grid to explicitly not read the file column?

public class Errors
{
//...
    private bool hasFile;
    public bool HasFile { get { return HasFile; } }
    private byte[] file;
    public byte[] File
    {
        get
        {
            if (HasFile) { file = FileHelper.DownloadAndDecompress(this.ID, "ErrorsDownloadFile"); }
            return file;
        }
        set { file = value; }
    }
    
    public static List<Errors> FindByAppName(string AppName, DateTime StartDate, DateTime EndDate) {/*...*/}
//...
}

I did some reading on Lazy<T> but, I'm struggling to get this to work into my regular workflow as when I implement it I can not assign to the setter the value to do file uploads...

Attempt but I can't assign a byte[] back to the File property as it is read only...

public bool HasFile { get { return HasFile; } }
public Lazy<byte[]> File
{
    get
    {
        if (HasFile) { return new Lazy<byte[]>(() => FileHelper.DownloadAndDecompress(this.ID, "ErrorsDownloadFile")); }
        else { return null; };
    }
    set { }
}

Any tips on how to properly implement a lazy property properly either using Lazy<T> or another method would be very much appreciated.

CodePudding user response:

If I understand you right, you want to implement lazy download, but eager upload

// Eager download (will be used in lazy download)
private byte[] DownLoad() {
  // download here:
  return FileHelper.DownloadAndDecompress(this.ID, "ErrorsDownloadFile");
}

// Lazy download ...   
private Lazy<byte[]> m_File;

// ... which we assign in the constructor
public MyClass() {
  ...
  m_File = new Lazy<byte[]>(Download); 
  ...
}

// Our property
public byte[] File {
  get {
    // Lazy download  
    return m_File.Value;
  }
  set {
    // we can't assign m_File.Value but we can recreate m_File
    m_File = new Lazy<byte[]>(value);

    //TODO: Upload here
  }
}
  • Related