namespace timer_and_thread {
///
public partial class MainWindow : Window
{
DispatcherTimer TimerObject;
Task[] tasks;
readonly object _countLock = new object();
int[] Summ = new int[10];
int Index = 0;
public MainWindow()
{
InitializeComponent();
TimerObject = new DispatcherTimer();
TimerObject.Tick += new EventHandler(timer_Elapsed);
TimerObject.Interval = new TimeSpan(0, 0, 5);
} // call the method every 5 seconds
private void timer_Elapsed(object sender, EventArgs e)
{
TimerObject.Stop();
BackgroundWorker backgroundWorkerObject = new BackgroundWorker();
backgroundWorkerObject.DoWork += new DoWorkEventHandler(StartThreads);
backgroundWorkerObject.RunWorkerAsync();
TimerObject.Start();
}
private void StartThreads(object sender, DoWorkEventArgs e)
{
tasks = new Task[4];
tasks[0] = Task.Factory.StartNew(() => DoSomeLongWork());
tasks[1] = Task.Factory.StartNew(() => DoSomeLongWork());
tasks[2] = Task.Factory.StartNew(() => DoSomeLongWork());
tasks[3] = Task.Factory.StartNew(() => DoSomeLongWork());
// Give the tasks a second to start.
Thread.Sleep(1000);
}
private void DoSomeLongWork()
{
while (Index < Summ.Length)
{
int localIndex = 0;
// lock the global variable from accessing by multiple threads at a time
lock (_countLock)
{
localIndex = Index;
Index++;
}
//I wrote rundom number generation just a an example of doing some calculation and getting some result. It can also be some long calculation.
Random rnd = new Random();
int someResult = rnd.Next(1, 100000);
// lock the global variable (Summ) to give it the result of calculation
lock (_countLock)
{
Summ[localIndex] = someResult;
}
}
}
// button by which I start the application working
private void Start_Button_Click_1(object sender, RoutedEventArgs e)
{
TimerObject.Start();
}
}
}
Replies
Know the answer? Post it — somebody with the same question will find it here.