0

I have a problem. I'm trying to make seekbar for BASS in C#.NET (WPF) but when I'm starting a new Thread it can't get access to modify value of my Slider or Label (with current song position value). Here is a Code:

//class:
Thread seekbar;
public Window1()
    {
        InitializeComponent();
        Bass.BASS_Init(-1, 44100, BASSInit.BASS_DEVICE_DEFAULT, IntPtr.Zero);

        seekbar = new Thread(new ThreadStart(this.ThreadTask));
        seekbar.IsBackground = true;
        seekbar.Start();
    }
private void ThreadTask()
    {
        int value = (int)Bass.BASS_ChannelGetPosition(music);
        while (true)
        {
            MusicSeekBar.Value = value; //MusicSeekBar is mine Slider
            CurrentValue.Content = value; //CurrentValue is a Label
        }
    }

I always get an error that thread can't get access to this two objects. Thanks for help in advice.

Kuba Wasilczyk
  • 1,118
  • 3
  • 11
  • 20

1 Answers1

3

You need to call the MusicSeekBar & CurrentValue in a Dispatcher beceause the new thread doesn't have access to them.

        Dispatcher.BeginInvoke(new Action(() =>
        {
            MusicSeekBar.Value = value; //MusicSeekBar is mine Slider
            CurrentValue.Content = value; //CurrentValue is a Label
        }));
DaveDev
  • 41,155
  • 72
  • 223
  • 385
  • I got an Out Of Memory message. – Kuba Wasilczyk Sep 18 '13 at 15:11
  • How many times does the loop iterate before the out of memory exception? – DaveDev Sep 18 '13 at 15:15
  • 2
    You are flooding the message pump, you need to either put a sleep in the while loop (do NOT put it inside the `BeginInvoke` block) or us `Invoke` instead of `BeginInvoke` so it will block until the update completes. Personally I would just have whatever updates `value` do the update to the UI, or have a event that gets fired when `value` is updated that updates the UI instead of looping. – Scott Chamberlain Sep 18 '13 at 15:15
  • Ok now it works. I just needed to add Thread.Sleep(1000); and works perfectly. Many thanks. – Kuba Wasilczyk Sep 18 '13 at 15:17