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

时间:2014-06-12 14:41:05

标签: c# multithreading wcf

我有WCF方法,它取所有玩家(客户)的分数,并将它们添加到它们的列表中进行排序。

但不幸的是,当第一个分数发送到服务器时,该功能将其添加到列表并将已排序的列表发送到客户端,不等待其他玩家的所有其他分数。 我试图使用async&等待,以便延迟该方法的持续约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);
    }

但它没有用,所以我该怎么办?

1 个答案:

答案 0 :(得分:0)

我已经创建了一个非常基本的服务作为样本,以展示如何实现您的目标。它是一种向您介绍lockManualResetEvent等结构的方法。

在我的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; }
    }
}

在我的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;

        }
    }
}

请注意,此示例的主要限制是它只允许在服务生命周期内播放单个游戏。我将为您运行多个游戏作为练习,但会指出您需要跟踪每个游戏现在正在完成的所有操作。您可能希望捆绑列表并等待锁定到对象,然后您可以以某种方式存储另一个列表,例如MemoryCache