Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access textbox from another method or Async

I'm somewhat new to C# and I'm having some issues retrieving a textbox value in an asynchronous method. I the thread to retrieve the text input in the UI and use it in the code. VS 2010 accepts my code but when I start to debug it gives me the following exception Invalid cross-thread access. Ideas? Am I missing something?

public void Response_Completed(IAsyncResult result)
{
    HttpWebRequest request = (HttpWebRequest)result.AsyncState;
    HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);

    using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
    {
        JObject rootObject = JObject.Load(new JsonTextReader(streamReader));

        string tracknum = trackid.Text; // Invalid cross-thread access exception
        string source = rootObject[tracknum]["source"].ToString();

        Deployment.Current.Dispatcher.BeginInvoke(() =>
        {
            //removed
        });
    }
}

Note: I'm attempting to do this on the Windows Phone 7 Platform

like image 351
ForeverLearning Avatar asked Aug 05 '26 14:08

ForeverLearning


1 Answers

You should to get textbox value on UI thread, instead of other threads. Invoke method executes the specified delegate on the UI thread:

string tracknum = (string)trackid.Invoke(new Func<string>(() => trackid.Text));

Edit:

On Windows Phone:

string tracknum = string.Empty;
Deployment.Current.Dispatcher.BeginInvoke(() =>
   {
       tracknum = trackid.Text;
       string source = rootObject[tracknum]["source"].ToString();
   });
like image 112
cuongle Avatar answered Aug 08 '26 18:08

cuongle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!