简体   繁体   English

如何等待WCF方法的所有响应?

[英]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 . 我有WCF方法,该方法将所有玩家(客户)的分数都添加到其中以进行排序。

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 : 我尝试使用async&await来将方法的继续延迟约30秒,如下所示:

 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 . 提供此方法是为了向您介绍诸如lockManualResetEvent构造。

In my ISudokuConcurrentService.cs: 在我的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: 在我的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 您可能希望将列表捆绑在一起并等待锁进入对象,然后可以通过某种方式(例如MemoryCache存储对象的另一个列表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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