I need to call a class method in a separate thread. The method has a parameter and a return value.
More details
I have a form with two TextBox. Put the user value in the first text block and get the result in the second:
private void tbWord_TextChanged(object sender, TextChangedEventArgs e) { tbResponce.Text = Wiki.DoWork(tbWord.Text); }
The wiki class should use the Wikipedia API:
public class Wiki { private class State { public EventWaitHandle eventWaitHandle = new ManualResetEvent(false); public String result; public String word; } private static void PerformUserWorkItem( Object stateObject ) { State state = stateObject as State; if(state != null) { Uri address = new Uri("http://en.wikipedia.org/w/api.php?action=opensearch&search=" + state.word); HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest; HttpWebResponse responce = (HttpWebResponse)request.GetResponse(); StreamReader myStreamReader = new StreamReader(responce.GetResponseStream(), Encoding.GetEncoding(1251)); state.result = myStreamReader.ReadToEnd(); state.eventWaitHandle.Set(); } } public static String DoWork(String _word) { State state = new State(); state.word = _word; ThreadPool.QueueUserWorkItem(PerformUserWorkItem, state); state.eventWaitHandle.WaitOne(); return state.result; } }
Problem
When a user presses keys in tbWord, the main form locks and waits for the Wiki class to do all the work.
How can I run DoWork asynchronously?
source share