简体   繁体   中英

How to wait for all responses of WCF Method ?

I have WCF method that take the scores of all players(clients) and add them to a list of them for sorting .

but Unfortunately when the first score sent to the server , the function add it to the list and sent the sorted list to the client , dose not wait for all other scores from other Players . i tried to use async & await in order to delay continuation of the method for about 30 seconds as the following :

 public  List<Player>  GetListOfWinners(int SentScore , string _SentPlayerID )
    {
        List<Player> PlayersList = new List<Player>();
        //Add to the List 
        PlayersList.Add(new Player { PlayerID = _SentPlayerID, Score = SentScore });

        DelayMethod();
        //Order It
        List<Player> SortedList = PlayersList.OrderByDescending(p => p.Score).ToList(); 
        // sent fULL SORTHEDlist to the Clients
        return SortedList;

    }

    private async void DelayMethod()
    {
        await Task.Delay(30000);
    }

but it dosn`t work , so what should i do ?

I've created a very basic service as a sample to show how you can accomplish some of your goal. It is provided as a means to introduce you to constructs such as lock and ManualResetEvent .

In my ISudokuConcurrentService.cs:

namespace SudokuTest
{
    using System.Collections.Generic;
    using System.Runtime.Serialization;
    using System.ServiceModel;

    [ServiceContract]
    public interface ISudokuConcurrentService
    {
        [OperationContract]
        SudokuGame ClientConnect();

        [OperationContract]
        List<Player> GetListOfWinners(int SentScore, string _SentPlayerID);
    }

    [DataContract]
    public class SudokuGame
    {
        [DataMember]
        public string PlayerID { get; set; }
        [DataMember]
        public int TimeLimitInSeconds { get; set; }
    }

    [DataContract]
    public class Player
    {
        [DataMember]
        public string PlayerID { get; set; }
        [DataMember]
        public int Score { get; set; }
    }
}

In my SudokuConcurrentService.svc.cs:

namespace SudokuTest
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading;

    public class SudokuConcurrentService : ISudokuConcurrentService
    {
        static int playerCount = 0;
        static List<Player> PlayersList = null;
        static object ListLock = new object();
        const int TimeLimit = 120;
        static ManualResetEvent AllPlayerResponseWait = new ManualResetEvent(false);

        public SudokuGame ClientConnect()
        {
            lock (ListLock)
            {
                if (PlayersList != null)
                {
                    // Already received a completed game response -- no new players.
                    return null;
                }
            }
            return new SudokuGame()
                {
                    PlayerID = "Player " + Interlocked.Increment(ref playerCount).ToString(),
                    TimeLimitInSeconds = TimeLimit
                };
        }

        public List<Player> GetListOfWinners(int SentScore, string _SentPlayerID)
        {
            lock (ListLock)
            {
                // Initialize the list.
                if (PlayersList == null) PlayersList = new List<Player>();

                //Add to the List 
                PlayersList.Add(new Player { PlayerID = _SentPlayerID, Score = SentScore });
            }

            // Now decrement through the list of players to await all responses.
            if (Interlocked.Decrement(ref playerCount) == 0)
            {
                // All responses received, unlock the wait.
                AllPlayerResponseWait.Set();
            }

            // Wait on all responses, as necessary, up to 150% the timeout (no new players allowed one responses received, 
            // so the 150% should allow time for the last player to receive game and send response, but if any players have 
            // disconnected, we don't want to wait indefinitely).
            AllPlayerResponseWait.WaitOne(TimeLimit * 1500);

            //Order It
            List<Player> SortedList = PlayersList.OrderByDescending(p => p.Score).ToList();
            // sent fULL SORTHEDlist to the Clients
            return SortedList;

        }
    }
}

Note that the main limitation of this sample is that it only allows a single game to be played during the life of the service. I'll leave running multiple games as an exercise for you, but will point out that you will need to track everything being done now per each game. You will likely want to bundle up the list and wait locks into objects, which you can then store another list of, in some manner such as MemoryCache

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