简体   繁体   中英

Awaiting on a task from a different class

I have a singleton class and a property that gets set from another class (class b), no problem. I want a different class (class a) to wait indefinitely until the property in the singleton class transitions true. I want the most efficient way possible of doing this, so I felt tasks were ideal, but I can't effectively put all of the pieces together. I don't want to continue to poll and sleep thread.sleep.

public class A
{
    public static void Main(string[] args)
    {
        if(!Monitor.Instance.HasChanged)
        {
            //await until the task in the Monitor class is complete
        }
    }
}

public class Monitor
{
    private static Monitor instance;
    private bool _hasChanged;
    private Monitor() { }

    public static Monitor Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new Monitor();
            }
            return instance;
        }
    }


    public bool HasChanged
    {
        get
        {
            return _hasChanged;
        }
        set
        {
            _hasChanged = value;
            if (_hasChanged)
            {
                //kick off a task
            }
        }
    }
}

public class B
{
    private static readonly Monitor _instance;
    public void DoSomething()
    {
        Monitor.Instance.HasChanged = true;
    }
}

I would use a TaskCompletionSource for this. You would do something like:

public class Monitor
{
    private TaskCompletionSource<bool> _changedTaskSource = new TaskCompletionSource<bool>();
    public Task HasChangedTask => _changedTaskSource.Task;

    public bool HasChanged
    ...
    set
    {
        ...
        _changedTaskSource.TrySetResult(true);
    }
}

This sets up a task completion source and completes the task when the value changes. You would wait on it like so:

await Monitor.Instance.HasChangedTask;

One thing that is not clear from your question and you will need to address is resetting the task. To do so, just re-create the TaskCompletionSource .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM