主程序和线程之间的无限循环

时间:2014-05-16 17:01:14

标签: c# multithreading

namespace MP3_speler.Threading
{
public class thread : MainWindow
{
    public thread() 
    {
        StartThreading();          
    }

    public void StartThreading() 
    {
        Thread thread = new Thread(new ThreadStart(WorkThreadFunction));
        thread.Priority = ThreadPriority.BelowNormal;
        thread.Start();            
    }

    public void WorkThreadFunction()
    {
        try
        {
            UpdateMyDelegatedelegate UpdateMyDelegate = new UpdateMyDelegatedelegate(UpdateMyDelegateLabel);
            timelabel.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, UpdateMyDelegate, (Convert.ToInt32(mp3FileReader.Position / 10000)));
            Thread.Sleep(500);
        }
        catch 
        {

        }
    }

    private void UpdateMyDelegateLabel(int i)
    {
        double timeseconds = (double)mp3FileReader.Position / (double)176000;

        TimeSpan t = TimeSpan.FromSeconds(timeseconds);

        string answer = string.Format("{0:D2}:{1:D2}:{2:D2}",
                        t.Hours,
                        t.Minutes,
                        t.Seconds
                        );

        timelabel.Content = answer;


        if (waveOut.PlaybackState != PlaybackState.Paused) Slider2.Value = mp3FileReader.Position;

    }
}
}

代码主程序:

 public partial class MainWindow : Window
  {
    public IWavePlayer waveOut;
    public Mp3FileReader mp3FileReader;
    public delegate void UpdateMyDelegatedelegate(int i);

    public MainWindow()
    {
        InitializeComponent();
        //Create a thread
        thread thread = new thread();
        //Setting up notifyicon
        notifyCenter notify = new notifyCenter(this);
        //giving values to bars
        Slider1.Value = 5;
        volumelabel.Content = 50;
    }

此代码生成无限循环并始终返回Initializecomponent。 也许问题是我让Thread类继承MainWindow但想知道问题是什么。

1 个答案:

答案 0 :(得分:0)

是的,thread派生自MainWindow的事实导致无限循环。

MainWindow的构造函数中,它会创建一个新的thread对象。但是,由于thread派生自MainWindow,因此会在创建MainWindow时重新调用thread的构造函数,无限重复广告。

请记住,在派生时,构造函数将始终调用基类默认构造函数,除非您明确指示使用其他构造函数。

顺便说一句,没有一个我可以想到永远来自MainWindow的用例,这肯定不是一个。您需要重新考虑您的设计。