private IAsyncResult RemoteAsyncCallStart(Node otherNode, int term, string url) { AsyncStartDelegate RemoteDel = new AsyncStartDelegate(otherNode.Vote); IAsyncResult RemAr = RemoteDel.BeginInvoke(term, url, null, null); return(RemAr); }
private void RunElection() { while (active) { node.IncrementTerm(); node.GetVoteResult(node.term, node.url); bool allAck = false; List <IAsyncResult> results = new List <IAsyncResult>(); List <WaitHandle> waits = new List <WaitHandle>(); foreach (Node otherNode in this.node.otherNodes) { IAsyncResult ar = RemoteAsyncCallStart(otherNode, this.node.term, this.node.url); results.Add(ar); waits.Add(ar.AsyncWaitHandle); } allAck = WaitHandle.WaitAll(waits.ToArray(), 2000); List <bool> count = new List <bool>(); foreach (IAsyncResult result in results) { AsyncStartDelegate del = (AsyncStartDelegate)((AsyncResult)result).AsyncDelegate; count.Add(del.EndInvoke(result)); } int countTrues = count.Where(item => item == true).Count() + 1; Console.WriteLine("Got votes! " + countTrues); if (countTrues > (count.Count + 1) / 2) { Console.WriteLine("I am the leader!"); this.node.SetState(new Leader(node)); } else { Console.WriteLine("election failed :c"); Thread.Sleep((new Random()).Next(500, 1000)); } } }