1 Replies - 6774 Views - Last Post: 18 August 2012 - 04:49 PM Rate Topic: -----

#1 Jankaaa  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 18-August 12

Call Dispatcher method with given parameters

Posted 18 August 2012 - 04:14 PM

Hello. I Created a simple wpf application some time ago wich find songs in website and return name, url and length. By learing new features in C# i would like to replace the search method to work in background (async), on new thread. However, to show the result on listbox i have to use Dispatcher.

This is how far i have done:

Start Searching for songs Async.
 public void SubmitSearch()
            AsyncCall ac = new AsyncCall(dc.AddToListBox);
            AsyncCallback acb = new AsyncCallback(CallBackWorker);
            ac.BeginInvoke(textBox1.Text, acb, null);

        public void CallBackWorker(IAsyncResult iar)

this is a "painful place".
string url, name, length;
// this method is called by custom event, where EachSongInstance is instance of song - Url, Name, Length
        void dc_OnListBox(object o, EachSongInstance e)
            url = e.Url;
            name = e.Name;
            length = e.Length;
            // this is how i call method, to add items on listBox.
            this.Dispatcher.BeginInvoke(new Action(WorkWithUiThread), DispatcherPriority.Normal);

        public void WorkWithUiThread()
            // Instance of UserControl
            ListBoxItem lbi = new ListBoxItem(url, name, length);

In result in listbox i get one song, many times. As far as i see, this is not the best practise to pass values from one method to other.
First of all, i would like to know, how can i call WorkWithUiThread() method with given parameters like WorkWithUiThread(string name, string url) using Dispatcher. And do there are any alternatives.

Is This A Good Question/Topic? 0
  • +

Replies To: Call Dispatcher method with given parameters

#2 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 5207
  • View blog
  • Posts: 13,954
  • Joined: 18-April 07

Re: Call Dispatcher method with given parameters

Posted 18 August 2012 - 04:49 PM

Well when you use the Action delegate you are encapsulating a method which takes no parameters and returns no value. So don't use that. Use the BeginInvoke() method which take a delegate, the priority, and then the parameters to pass. You will see the overloads there for that method. The BeginInvoke(Delegate, Priority, Object[]) overload. The object array is the parameters to pass to the method.


Was This Post Helpful? 1
  • +
  • -

Page 1 of 1