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
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With