locked
Variables change back to there initializations after function completes, please help. RRS feed

  • Question

  • User246147646 posted

    Well it looks like I have nearly completed my first SignalR project.  Researching GitHub projects was very helpful to me.  I am having a problem with global variables in C#.  After the function completes, the global variables lose their values and become what they were initialized as.  Please help, I'm finally almost there!

    Thanks, Josh

    Monday, December 30, 2019 12:56 AM

All replies

  • User61956409 posted

    Hi Josh,

    I am having a problem with global variables in C#.  After the function completes, the global variables lose their values and become what they were initialized as. 

    Please clarify more about the issue with your relevant code, so that we can understand and help fix the issue better.

    With Regards,

    Fei Han

    Monday, December 30, 2019 1:52 AM
  • User246147646 posted

    For example,  the following initializations of :

    namespace SignalRChat.Hubs
    {
    public class ChatHub : Hub
    {
    public String PlayerOneConnId = "10"; public String PlayerTwoConnId = "10";

    become the values of these variables again, after this function:

    public async Task Register()
            {
                Clients A_Client = new Clients();
                A_Client.ConnectionId = Context.ConnectionId;
                //A_Client.Name = "a";
                ClientList.Add(A_Client);
                //hides button
                //asynch
                await Clients.Caller.SendAsync("IsRegister");
                var flag1 = 0;
                //foreach (Clients element in ClientList)
                for (int k = ClientList.Count - 1; k >= 0; --k)
                {
                    //PlayerOneConnId = "";
                    //PlayerTwoConnId = "";
    
                    //not the current user - open page, gets removed after used
                    if ((ClientList[k].ConnectionId) != (Context.ConnectionId))
                    {
                        PlayerOneConnId = (ClientList[k].ConnectionId);
                        PlayerTwoConnId = (Context.ConnectionId);
    
                        GetGroups();
                        EachGame Game1 = new EachGame();
    
                        //check these:
                        Game1.Playertwoconn = PlayerTwoConnId;
                        Game1.Playeroneconn = PlayerOneConnId;
                        Game1.Groupname = groupname;
                        Games.Add(Game1);
    
                        
                        await Groups.AddToGroupAsync(PlayerTwoConnId, groupname);
                        await Groups.AddToGroupAsync(PlayerOneConnId, groupname);
                        integer++;
                        //firstregister = 1;
    
                        //remove other player
                        ClientList.RemoveAt(k);
                        //remove current player flag
                        flag1 = 1;
                        break;
                    }
                }
                //there was another player so remove other
                if (flag1 == 1)
                {
                    flag1 = 0;
    
                    for (int j = ClientList.Count - 1; j >= 0; --j)
                    {
    
                        if ((ClientList[j].ConnectionId) == (Context.ConnectionId))
                        {
                            //removes current player
                            ClientList.RemoveAt(j);
                            //prints names
    
                            await Clients.Client(PlayerOneConnId).SendAsync("Printnames1");
                            whoseturn = PlayerOneConnId.ToString();
                            await Clients.Client(PlayerTwoConnId).SendAsync("Printnames2");
                            await Clients.Client(PlayerOneConnId).SendAsync("Enablebuttons");
                            await Clients.Client(PlayerTwoConnId).SendAsync("Enablebuttons");
                            buttonAnswer = random.Next(1,6);
    
                            break;
                        }
    
                    }
                }
    
    
    
    
    
            }
    
        }

    Monday, December 30, 2019 1:59 AM
  • User61956409 posted

    Hi Josh,

    You just share the code of your SignalR Hub, without include your client side code, please include it in your post, so that we can reproduce the issue based on it.

    With Regards,

    Fei Han

    Tuesday, December 31, 2019 6:07 AM
  • User246147646 posted
    "use strict";
    
    
    
    var integer = 0;
    var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();
    
    
    
    
    //Disable send button until connection is established
    document.getElementById("sendButton").disabled = true;
    
    
    
    
    connection.on("ReceiveMessage", function (user, message) {
        var msg = message.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
        var encodedMsg = user + " says " + msg;
        var li = document.createElement("li");
        li.textContent = encodedMsg;
        document.getElementById("messagesList").appendChild(li);
    });
    
    
    
    connection.on("IsRegister", function () {
    
    
        $('#registerButton').hide();
    
    
    });
    
    connection.on("IsWaiting", function () {
    
    
        $('#registerButton').show();
    
    
    });
    
    
    connection.on("Printnames0", function () {
    
        //$('#registerButton').hide();
        $("#messagesList").html("1  ");
    
    });
    
    
    connection.on("Printnames1", function () { 
    
        //$('#registerButton').hide();
        $("#messagesList").html("It's your turn!!");
    
    });
    
    connection.on("Printnames2", function () {
    
        //$('#registerButton').hide();
        $("#messagesList").html("It's not your turn!!");
    
    });
    
    ////
    
    connection.on("Enablebuttons", function () {
    
        
        $('#one').prop('disabled', false);
        $('#two').prop('disabled', false);
        $('#three').prop('disabled', false);
        $('#four').prop('disabled', false);
        $('#five').prop('disabled', false);
        
    
    });
    
    ////
    
    connection.on("IsButton1_1", function (message) {
        if (message == "won")
        {
            $("#messagesList").html("You have won!");
        }
        else
        {
            $('#one').prop('disabled', true);
        }
    });
    
    connection.on("IsButton1_2", function (message) {
        if (message == "won")
        {
            $("#messagesList").html("You have lost!");
        }
        else
        {
            $('#one').prop('disabled', true);
        } 
    });
    ////////////////
    
    connection.on("IsButton2_1", function (message) {
        if (message == "won") {
            $("#messagesList").html("You have won!");
        }
        else {
            $('#two').prop('disabled', true);
        }
    });
    
    connection.on("IsButton2_2", function (message) {
        if (message == "won") {
            $("#messagesList").html("You have lost!");
        }
        else {
            $('#two').prop('disabled', true);
        }
    });
    
    connection.on("IsButton3_1", function (message) {
        if (message == "won") {
            $("#messagesList").html("You have won!");
        }
        else {
            $('#three').prop('disabled', true);
        }
    });
    
    connection.on("IsButton3_2", function (message) {
        if (message == "won") {
            $("#messagesList").html("You have lost!");
        }
        else {
            $('#three').prop('disabled', true);
        }
    });
    
    connection.on("IsButton4_1", function (message) {
        if (message == "won") {
            $("#messagesList").html("You have won!");
        }
        else {
            $('#four').prop('disabled', true);
        }
    });
    
    connection.on("IsButton4_2", function (message) {
        if (message == "won") {
            $("#messagesList").html("You have lost!");
        }
        else {
            $('#four').prop('disabled', true);
        }
    });
    
    connection.on("IsButton5_1", function (message) {
        if (message == "won") {
            $("#messagesList").html("You have won!");
        }
        else {
            $('#five').prop('disabled', true);
        }
    });
    
    connection.on("IsButton5_2", function (message) {
        if (message == "won") {
            $("#messagesList").html("You have lost!");
        }
        else {
            $('#five').prop('disabled', true);
        }
    });
    
    ////////////////
    
    connection.start().then(function () {
        document.getElementById("sendButton").disabled = true;
    }).catch(function (err) {
        return console.error(err.toString());
    });
    
    
    
    document.getElementById("sendButton").addEventListener("click", function (event) {
        var user = document.getElementById("userInput").value;
        var message = document.getElementById("messageInput").value;
        connection.invoke("SendMessage", user, message).catch(function (err) {
            return console.error(err.toString());
        });
        event.preventDefault();
    });
    
    
    document.getElementById("registerButton").addEventListener("click", function (event) {
    
        connection.invoke("Register").catch(function (err) {
            return console.error(err.toString());
        });
        event.preventDefault();
    });
    
    
    document.getElementById("one").addEventListener("click", function (event) {
    
        connection.invoke("B1").catch(function (err) {
            return console.error(err.toString());
        });
        event.preventDefault();
    });
    
    ///////////////
    document.getElementById("two").addEventListener("click", function (event) {
    
        connection.invoke("B2").catch(function (err) {
            return console.error(err.toString());
        });
        event.preventDefault();
    });
    
    document.getElementById("three").addEventListener("click", function (event) {
    
        connection.invoke("B3").catch(function (err) {
            return console.error(err.toString());
        });
        event.preventDefault();
    });
    
    document.getElementById("four").addEventListener("click", function (event) {
    
        connection.invoke("B4").catch(function (err) {
            return console.error(err.toString());
        });
        event.preventDefault();
    });
    
    document.getElementById("five").addEventListener("click", function (event) {
    
        connection.invoke("B5").catch(function (err) {
            return console.error(err.toString());
        });
        event.preventDefault();
    });
    
    ///////////////

    Tuesday, December 31, 2019 5:56 PM
  • User246147646 posted

    Also, https://github.com/josheirm/SignalRChat_Start.      (master)

    Tuesday, December 31, 2019 6:04 PM
  • User61956409 posted

    Hi Josh,

    You can try to declare them as static, like below, and check if it can help fix the issue.

    public static string PlayerOneConnId = "10";
    public static string PlayerTwoConnId = "10";

    With Regards,

    Fei Han

    Wednesday, January 1, 2020 8:14 AM
  • User246147646 posted

    I have tried that, and I can't play more than one game at a time.

    Wednesday, January 1, 2020 2:15 PM
  • User246147646 posted

    I set my variables:

    namespace SignalRChat.Hubs
    {
        public class ChatHub : Hub
        {
            public String PlayerOneConnId = "10";
            public String PlayerTwoConnId = "10";
    
    

    After they are used and a function completes they return to the above values.  Do I need to set up my project again, or is this normal, with a solution for me?  I need the variables to keep there values after the function completes.

    Thanks, Josh

    Wednesday, January 1, 2020 2:43 PM
  • User246147646 posted

    The answer is:  Hubs are transient.  When a new function is called the values are not maintained.

    Saturday, January 4, 2020 12:44 AM