Is there any class in the .NET Framework to represent a container for storing objects?

I am looking for a class that defines the holding structure for an object. The value for this object can be set later than when creating this container. It is useful to pass such a structure to lambdas or in callback functions, etc.

Say:

class HoldObject<T> {
 public T Value { get; set; }
 public bool IsValueSet();
 public void WaitUntilHasValue();
}

// and then we could use it like so ...

HoldObject<byte[]> downloadedBytes = new HoldObject<byte[]>();
DownloadBytes("http://www.stackoverflow.com", sender => downloadedBytes.Value = sender.GetBytes());

Defining this structure is pretty easy, but I'm trying to figure out if it is available in FCL. I also want this to be an efficient structure that has all the necessary functions, such as thread safety, efficient wait, etc.

Any help is greatly appreciated.

+3
source share
2 answers

, .

public class ObjectHolder<T>
{
    private T value;
    private ManualResetEvent waitEvent = new ManualResetEvent(false);

    public T Value
    {
        get { return value; }
        set
        {
            this.value = value;

            ManualResetEvent evt = waitEvent;

            if(evt != null)
            {
                evt.Set();
                evt.Dispose();
                evt = null;
            }
        }
    }

    public bool IsValueSet
    {
        get { return waitEvent == null; }
    }

    public void WaitUntilHasValue()
    {
        ManualResetEvent evt = waitEvent;

        if(evt != null) evt.WaitOne();
    }
}
+3

, , . CTP.NET 4.0 TPL Future<T>. RTM.NET 4.0 Task<T>. , :

class HoldObject<T>
{
    public T Value { get; set; }
    public bool IsValueSet();
    public void WaitUntilHasValue();
}

class Task<T>
{
    public T Value { get }
    public bool IsCompleted { get; }
    public void Wait();
}

.NET 4.0, Reactive Extensions for.NET 3.5sp1. System.Threading.dll, TPL .NET 3.5.


Value , , , , . , , , :
var downloadBytesTask = Task<byte[]>.Factory.StartNew(() => 
    DownloadBytes("http://www.stackoverflow.com"));

if (!downloadBytesTask.IsCompleted)
{
    downloadBytesTask.Wait();
}

var bytes = downloadBytesTask.Value;
+3

Source: https://habr.com/ru/post/1744656/


All Articles