0

I am programming a Web Application with ASP.NET and C#.

When the page loads, it has to listen (IP connection) and when it gets a message, a label should be updated with that value (update the UI from the callback). Simplifying my code, I have this for the mainpage:

protected void Page_Load(object sender, EventArgs e)
    {
        Thread listeningThread = new Thread(new ThreadStart(StartListening));
        listeningThread.Start();
    }

This is the label in the aspx file:

<asp:Label ID="MyLabel" runat="server" EnableViewState="False"></asp:Label>

Then, this is my function for the callback:

private void StartListening()
    {
        Action<string> callbackRead = (string message) =>
        {
            myLabel.text = message;
        };
    }

The message arrives properly and if I put a breakpoint inside the callback I can see how it goes inside it. Despite of this, UI is not updated. Of course, if I write myLabel.text = "Whatever"; in the Page_Load part, it works fine.

I have tried with a grid and DataSource + DataBind() (I followed this tutorial) but I still have the same problem, it works fine if I do it in the Page_Load but not from the callback.

I have read a lot about this in another questions but non of the answers solves my problem (most are for WinForms, etc.)

I'm new in this field and I know I'm probably missing something. Could you help me, please? How is the right way to achieve what I want? Thanks in advance!

serfe
  • 285
  • 5
  • 13
  • The proper way to achieve this is [SignalR](http://signalr.net/). – Sergei Rogovtcev Aug 16 '16 at 14:45
  • I use SignalR for other parts of the project but didn't think about this one, I'll try. – serfe Aug 16 '16 at 14:54
  • I've been trying using this: var context = GlobalHost.Connectio‌​nManager.GetHubContex‌​t(‌​); context.Clients.All.‌​broadcastMessage("nam‌​e", "message"); but it does nothing. It only works if I use it outside from the callback, like for example, when I press a button. – serfe Aug 17 '16 at 10:26

1 Answers1

2

By setting myLabel.text = message you update label text on the server side while you [also] need to update text in client browser(s).

Typical approaches here are: ajax pulling (you send ajax requests each X seconds to server to check for updates) or websockets (your server can push updates directly to client browsers).

Community
  • 1
  • 1
serhiyb
  • 4,753
  • 2
  • 15
  • 24
  • But when I set the text = "message" directly in the Page_Load, it works for the UI too without any ajax pulling or websockets help. – serfe Aug 16 '16 at 14:45
  • Correct, because Page_Load happens before actual HTML is rendered while your background worker can update it after. – serhiyb Aug 16 '16 at 14:46