This should be pretty easy , but i couldn’t find a adequated term to search for… Well I’m new to C# and i’m trying to make a simple App to write the return of a webservice.
I came across the need to use a Thread… passing parameters to the thread is fairly easy , I couldn’t find a way to return from the Threaded method and update my UI to show the result (well actually no the real result for now)
The event:
private void TextBox_TextChanged_1(object sender, TextChangedEventArgs e)
{
minhaSigla = Sigla.Text;
Task.Factory.StartNew(() => GetQuoteAndUpdateText(minhaSigla));
tb1.Text = "UIElement-TO-UPDATE";
}
And then the Threaded method
private string GetQuoteAndUpdateText(string sign)
{
string SoapEnvelope = "";
SoapEnvelope = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
SoapEnvelope += "<soap:Envelope ";
SoapEnvelope += "xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\" ";
SoapEnvelope += "xmlns:xsd= \"http://www.w3.org/2001/XMLSchema\" ";
SoapEnvelope += "xmlns:soap= \"http://schemas.xmlsoap.org/soap/envelope/\">";
SoapEnvelope += "<soap:Body>";
SoapEnvelope += " <GetQuote xmlns=\"http://www.webserviceX.NET/\"> ";
SoapEnvelope += " <symbol>" + sign + "</symbol> ";
SoapEnvelope += " </GetQuote> ";
SoapEnvelope += "</soap:Body>";
SoapEnvelope += "</soap:Envelope>";
EndpointAddress endpoint = new EndpointAddress("http://www.webservicex.net/stockquote.asmx");
BasicHttpBinding basicbinding = new BasicHttpBinding();
basicbinding.SendTimeout = new TimeSpan(3000000000);
basicbinding.OpenTimeout = new TimeSpan(3000000000);
stockbyname.StockQuoteSoapClient sbn = new stockbyname.StockQuoteSoapClient(basicbinding, endpoint);
XmlDocument xmlDocument = new XmlDocument();
return sbn.GetQuote(SoapEnvelope);
}
Also any information will be much appreciated, even comments about how awful my code is 😛
Without getting into all the fun async/await stuff, you can use the ContinueWith method of Task to handle the returned information.
As I mention in the above code sample, depending on which UI technology you’re using you’ll need to use a dispatcher to avoid getting an illegal cross thread access exception.
WinForms example of the expression inside the
.ContinueWith(using the Invoke method of Control)WPF example of the expression inside the
.ContinueWith(using WPF’s Dispatcher)Silverlight/Windows Phone example of the expression inside the
.ContinueWith(using Silverlight’s Dispatcher)Windows Store example of the expression inside the
.ContinueWith(using CoreDispatcher)