返回实例,修改C#中的一些属性

时间:2016-08-17 12:45:39

标签: c# azure-service-fabric

我想知道C#中的成语。我编写了与远程代理相关的代码。

public Task SetIndexAsync(int index)
{
    var state = this.StateManager.TryGetStateAsync<ActorState>("MyState").GetAwaiter().GetResult().Value;

    if (state == null)
    {
        state = new ActorState() { Temperature = 0 };
    }
    state.Index = index;
    this.StateManager.SetStateAsync<ActorState>("MyState", state);
    return Task.FromResult(true);
}

这不酷。 :(

我试着这样写。但是,它仍然不酷。

private ActorState StateProxy
{
    get
    {
        return this.StateManager.TryGetStateAsync<ActorState>("MyState").GetAwaiter().GetResult().Value;
    }

    set
    {
        this.StateManager.AddOrUpdateStateAsync<ActorState>("MyState", value, (k, v) => value)
    }
}

public Task SetIndexAsync(int index)
{
    Func<ActorState, int, ActorState> addIndex = (state, idx) => { state.Index = idx; return state; };
    addIndex(StateProxy, index);
    return Task.FromResult(true);
}

如果我可以编写一个通过修改属性返回实例的单行程序, 它可能会更好。或者为此提出一个很酷的解决方案的想法?

1 个答案:

答案 0 :(得分:0)

最后,我决定这样做。我记得ActiveRecord的设计。

    internal sealed class ActorState
    {
        [DataMember]
        public List<string> PartitionNames { get; set; }
        [DataMember]
        public Dictionary<string, DateTime> PartitionLeases { get; set; }

        private IActorStateManager stateManager;

        internal static ActorState GetState(IActorStateManager stateManager)
        {                
           var state = stateManager.GetStateAsync<ActorState>("MyState").GetAwaiter().GetResult();
            state.stateManager = stateManager;
            return state;
        }
        internal void Save()
        {
            stateManager.AddOrUpdateStateAsync<ActorState>("MySate", this, (k,v) => this ).GetAwaiter();
        }
    }

用法:

        var stateProxy = ActorState.GetState(this.StateManager);
        List<string> keys = stateProxy.PartitionLeases.Keys.ToList();
        foreach(string key in keys)
        {
            if (DateTime.Now - stateProxy.PartitionLeases[key] >= TimeSpan.FromSeconds(60))
                stateProxy.PartitionLeases.Remove(key);

        }
        stateProxy.Save();