C# 主程序和线程之间的无限循环
主程序代码:C# 主程序和线程之间的无限循环,c#,multithreading,C#,Multithreading,主程序代码: namespace MP3_speler.Threading { public class thread : MainWindow { public thread() { StartThreading(); } public void StartThreading() { Thread thread = new Thread(new ThreadStart(WorkThreadFunc
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;
}
}
}
这段代码生成一个无限循环并始终返回Initializecomponent。
可能问题是我让Thread类继承了MainWindow,但想知道问题出在哪里。是的,
Thread
派生自MainWindow
这一事实导致了无限循环
在main窗口
的构造函数中,它创建一个新的线程
对象。但是,由于线程
派生自主窗口
,因此它会重新调用主窗口
的构造函数,当创建线程
时,会无限重复
请记住,在派生时,除非明确指示使用不同的构造函数,否则构造函数将始终调用基类默认构造函数
顺便说一句,我想不出从
MainWindow
派生出任何用例,而这肯定不是一个。您需要重新考虑您的设计。谢谢,我只是想确定一下!您可以尝试将public-class-thread:MainWindow
更改为public-partial-class-MainWindow:Window
,去掉thread()
构造函数并调用StartThreading()代码>在主窗口构造函数中。但不确定“名称空间MP3\u speler.Threading”名称空间将如何工作。@MikeofSST,他显然在同一个名称空间中,所以这部分没问题。我不认为这样做有什么好处(除了拆分代码文件(这真的是件好事吗?),但它会起作用。@BradleyDotNET感谢您的确认。我也看不到它的好处(我自己把它放在ViewModel中,因为我在应用程序中使用了无代码隐藏视图)。这似乎是isa/hasa问题的一个快速解决方案。:-)
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;
}