开发者

How to update value in textBox in ASP.NET from other threads?

I'm using ASP.NET 4.0 on IIS7.5 and WCF Callback technique. I have no problem with callback. The wcf service can fire callback method in web client but it seems it's on another thread 开发者_StackOverflow中文版with the UI thread.

public partial class _Default : System.Web.UI.Page, IServiceCallback
{
    private IService proxy = null;
    private static TextBox _textBoxtest;

    protected void Page_Load(object sender, EventArgs e)
    {
        _textBoxtest = TextBox1;
    }      

    protected void Button1_Click(object sender, EventArgs e)
    {
        //then server will call back to FireCallBackFromServer
        proxy.CallService(type, "someObject");
    }

    #region IServiceCallback Members

    public void FireCallBackFromServer(string txt)
    {
        TextBox1.Text = txt; <-- the value does not update on textBox
    }

    #endregion
}

Please help me to think how to update my textBox from callback event.

Thank you.


It is how WCF callback works. Each callback call is served by its own thread. I think the reason why this happens is because you don't have SynchronizationContext which will point incomming request back to current thread (and hopefully current instance of your page). The contrary example are callbacks used in WPF or WinForm applications. UI thread in these applications by default has SynchronizationContext so if you open service proxy in UI thread, requests to callback are routed back to UI thread - it sometimes causes another problems so you can turn off usage of SynchronizationContext in ServiceBehaviorAttribute.

But even if you solve this problem you will deal with the same problem in ASP.NET. Each request to ASP.NET creates new instance of handler. So each request from your browser will create new instance of page.

I believe that if client is ASP.NET then WCF callback doesn't make sense because I still didn't see any working implementation.


I've run into this issue, where only the UI thread can perform UI updates, in a WPF application using WCF callbacks. I don't do much work in ASP.NET, so I'm not 100% sure the answer is the same but the problem looks very similar.

The way I solved the problem was to use the Dispatcher and lambdas to send the change to the UI thread. Put into the context of your code, it would look something like

public void FireCallBackFromServer(string txt)
{
    Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() => TextBox1.Text = txt;));
}

This should update your textbox's content to the text provided in the callback. Give it a try and see how you go.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜