Call a method in a separate thread

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?

+4
source share
6 answers

Or use TPL as follows:

 private void tbWord_TextChanged(object sender, TextChangedEventArgs e) { Task.Factory.StartNew(() => { return Wiki.DoWrok(tbWord.Text); }).ContinueWith(taskState => { tbResponce.Text = taskState.Result; }, TaskScheduler.FromCurrentSynchronizationContext()); } 

see http://msdn.microsoft.com/en-us/library/dd997394.aspx

+9
source

Take a look at using the BackgroundWorker class. This will allow you to do asynchronous work. You can then update your user interface in the dispatcher thread when you receive a BackgroundWorker notification that the operation has completed.

+2
source

Also take a look at HttpWebRequest.BeginGetResponse and its associated methods for asynchronously executing web requests. This would eliminate the need for any custom background processing.

+1
source

You can use the WPF manager to perform the operation in the main interface thread, since you are already using WaitOne() in DoWork - the main DoWork operation will be synchronous, so you can use Dispatcher.BeginInvoke() to asynchronously change the changes in the user interface:

 Dispatcher.CurrentDispatcher.BeginInvoke( DispatcherPriority.Input, new ThreadStart(() => { tbResponce.Text = Wiki.DoWork(tbWord.Text); })); 

Please let me know if this works for you, as Polity has mentioned some possible sync issues.

0
source

Don't wait for the ThreadPool thread to end in your UI thread, but instead, subscribe to the full event:

 class Program { static void Main(string[] args) { var program = new Program(); program.DoWorkComplete += (s, e) => Console.WriteLine(e.Result); program.DoWorkAsync(); // Wait 10 seconds, worker thread should finish beforehand, so // you see console output Thread.Sleep(10000); } public event EventHandler<CompleteEventArgs> DoWorkComplete; public void DoWorkAsync() { ThreadPool.QueueUserWorkItem(o => { // Download data here string result = "Result from Wiki"; if(DoWorkComplete != null) DoWorkComplete(this, new CompleteEventArgs(result)); }); } public class CompleteEventArgs : EventArgs { public CompleteEventArgs(string result) { this.Result = result; } public string Result { get; private set; } } } 

Edit: This is a console application. I can WriteLine from any thread. If you are working with WPF, you need to use Dispatcher to make sure that you are handling the DoWorkComplete event in the user thread ( sll is already specified ). If you are working with Windows Forms, you must do the same with Control.Invoke .

0
source

you can use an asynchronous call to achieve just that,

http://support.microsoft.com/kb/315582

0
source

Source: https://habr.com/ru/post/1397400/


All Articles