Help😠 Dynamic Event Subscribing

Posts 1–13 of 13 · Page 1 of 1
😠 Dynamic Event Subscribing
Basically it won't let me subscribe to the event in my DogWatcher class. I have a list<> that handles the WatchDog. When I fire up my application it doesn't have any "dogs" to watch. When the user adds an application it calls the Add function which makes a new WatchDog object and then adds it to the dynamic list and trys to subscribe to it. It doesn't fire an exception I believe but it just keeps throwing null error when my code calls the Event in the WatchDog class, because there are no subscribers. Can anybody point me in the right direction?

Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Threading;
using System****;
using System.Reflection;

namespace Idle_Master
{
    public delegate void DogStateChangeD(GameProfile profile, DogState state, bool change);

    public enum DogState { Running, Idle };

    class WatchDog
    {
        private GameProfile _profile = null;
        private Process _process = null;
        //
        private string FileNameNoExt = null;
        private Thread IdleChecker = null;
        private System.Threading.Timer StartWatcher;
        //
        public event DogStateChangeD DogStateChange;

        public WatchDog(GameProfile profile_) : this(profile_, null) { }

        public WatchDog(GameProfile profile_, Process process_)
        {
            _profile = profile_;
            if (process_ != null) { _process = process_; }
            //
            FileNameNoExt = Path.GetFileNameWithoutExtension(_profile.Path);
            StartWatcher = new Timer(new TimerCallback(StartWatcher_Tick));
            IdleChecker = new Thread(new ThreadStart(threadedIdleWait));
            //
            if (isRunning) { IdleChecker.Start(); DogStateChange(_profile, DogState.Running, true); }
            else { StartWatcher.Change(250, 1000); DogStateChange(_profile, DogState.Running, false); }
        }

        private void StartWatcher_Tick(object state)
        {
            if (isRunning) { IdleChecker.Start(); DogStateChange(_profile, DogState.Running, true); } 
        }

        private void _process_Exited(object sender, EventArgs e)
        {
            IdleChecker.Abort();
            StartWatcher.Change(250, 1000);
            DogStateChange(_profile, DogState.Running, false);
        }

        public GameProfile Profile { get { return _profile; } }

        public Process Game_Process
        {
            get { return _process; }
            set { _process = value; }
        }

        public bool isRunning
        {
            get
            {
                if (_process == null)
                {
                    Process[] runningProcs = Process.GetProcessesByName(FileNameNoExt);
                    if (runningProcs.Length > 0)
                    {
                        _process = runningProcs[0];
                        _process.Exited += _process_Exited;
                        return true;
                    }
                    else { return false; }
                }
                else { return (_process.HasExited) ? false : true; }
            }
        }

        private void threadedIdleWait()
        {
            DateTime idleTime = new DateTime(1, 1, 1);
            while (1 == 1)
            {
                if (_process.WaitForInputIdle(0))
                {
                    if (idleTime.Year == 1)
                    {
                        idleTime = DateTime.Now;
                    }
                    else
                    {
                        if (DateTime.Now.Subtract(idleTime).TotalSeconds > 2) //TODO: > Settings.IdleTime
                        {
                            DogStateChange(_profile, DogState.Idle, true);
                        }
                    }
                }
                else
                {
                    idleTime = new DateTime(1, 1, 1);
                    DogStateChange(_profile, DogState.Idle, false);
                }
                Thread.Sleep(500);
            }
        }
    }

    public class DogWatcher
    {
        List<WatchDog> WatchList = new List<WatchDog>();
        //
        public event DogStateChangeD DogStateChange;

        public void Add(GameProfile gp)
        {
            WatchList.Add(new WatchDog(gp));
            WatchList[WatchList.Count - 1].DogStateChange += DogWatcher_DogStateChange;
        }

        private void DogWatcher_DogStateChange(GameProfile profile, DogState state, bool change)
        {
            DogStateChange(profile, state, change);
        }
    }
}
A secure way to call an event:
Code:
ThreadPool.QueueUserWorkItem(delegate{
     if(DogStateChanged != null)
     {
          //call the event...
     }
});
Yea the ArgumentNullException isn't the problem though. If it had a subscriber it wouldn't throw an error. I could also also do

Code:
public event DogStateChangeD DogStateChange = delegate { };
Which would have a default subscriber and never raise an exception. I want to know why in my DogWatcher class it doesn't subscribe to the event. Thanks for your example though.
Can you be a little more specific I cannot understand you, what do you mean with "subscribe" to the event...
In the Add function this line is subscribing

Code:
WatchList[WatchList.Count - 1].DogStateChange += DogWatcher_DogStateChange;
Adding a handler, etc. I have also tried creating the DogWather obj first then adding to the list.
Quote Originally Posted by tlokzz View Post
In the Add function this line is subscribing

Code:
WatchList[WatchList.Count - 1].DogStateChange += DogWatcher_DogStateChange;
Adding a handler, etc. I have also tried creating the DogWather obj first then adding to the list.
Have you tried "+= new DogStateChangeD(DogWatcher_DogStateChange);"....So metimes the less logical way is the best.
Still saying same thing, *********enceException (Object reference not set to an instance of an object.)
Quote Originally Posted by tlokzz View Post
Still saying same thing, *********enceException (Object reference not set to an instance of an object.)
I really can't figure out what's wrong....:/ Try to include the GamerProfile class too?
Quote Originally Posted by user590177 View Post


I really can't figure out what's wrong....:/ Try to include the GamerProfile class too?
Code:
    #region GameProfile (object)

    public class GameProfile
    {
        private string _name;
        private string _path;

        public GameProfile(string name_, string path_)
        {
            _name = name_;
            _path = path_;
        }

        public string Name
        {
            get { return _name; }
        }

        public string Path
        {
            get { return _path; }
        }
    }

    #endregion
I should prob use a struct for that? I doubt it's the problem though.

I know Classes pass references and structs pass the actual obj. I still don't know fully when to use them though. Learning new techniques as I go.
Are you sure that you can access a thread like every other fields? Why don't you use a variable instead of that?
like:
Code:
private bool exit = false;


        private void threadedIdleWait()
        {
            DateTime idleTime = new DateTime(1, 1, 1);
            while (1 == 1)
            {
            if(exit)
            {
               Thread.CurrentThread.Abort();
            } else 
            {
               if (_process.WaitForInputIdle(0))
                {
                    if (idleTime.Year == 1)
                    {
                        idleTime = DateTime.Now;
                    }
                    else
                    {
                        if (DateTime.Now.Subtract(idleTime).TotalSeconds > 2) //TODO: > Settings.IdleTime
                        {
                            DogStateChange(_profile, DogState.Idle, true);
                        }
                    }
                }
                else
                {
                    idleTime = new DateTime(1, 1, 1);
                    DogStateChange(_profile, DogState.Idle, false);
                }
                Thread.Sleep(500);
            }
            }
        }
    }

        private void _process_Exited(object sender, EventArgs e)
        {
            exit = true;
            StartWatcher.Change(250, 1000);
            DogStateChange(_profile, DogState.Running, false);
        }
I think the problem is this tho,,, if you want to access different threads on the main one use the thread synchronization.
http://msdn.microsoft.com/en-us/libr...(v=vs.80).aspx
I doubt that would fix it. I found some new info though in the Add function it doesn't seem to even get to Subscribe line it throws an exception on the first line.

I wrapped it in try/catch

Code:
        public void Add(GameProfile gp)
        {
            try
            {
                WatchList.Add(new WatchDog(gp));
                WatchList[WatchList.Count - 1].DogStateChange += DogWatcher_DogStateChange;
            }
            catch (Exception e) { System.Windows.Forms.MessageBox.Show(e.Message); }
        }
it shows object null reference exception.. so I believe it is my GameProfile class maybe.... hmmm I hate debugging.. here is the form code also... I think only thing missing is designer code and the full Settings class

Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Idle_Master
{
    public partial class MainForm : Form
    {
        DogWatcher Leashes;

        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            Leashes = new DogWatcher();
            Leashes.DogStateChange += Leashes_DogStateChange;
            //
            listView1.Items.Add(new ListViewItem(new string[] { "Chromium Updater", "True", "False" }));
            Leashes.Add(new GameProfile("Chromium Updater", "C:\\Chromium Updater.exe"));
        }

        private void Leashes_DogStateChange(GameProfile profile, DogState state, bool change)
        {
            if (InvokeRequired)
            {
                BeginInvoke(new DogStateChangeD(Leashes_DogStateChange), new object[] { profile, state, change });
                return;
            }
            //
            foreach (ListViewItem item in listView1.Items)
            {
                if (item.SubItems[0].Text == profile.Name) { item.SubItems[2].Text = change.ToString(); break; }
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            //Settings
        }
    }
}
Quote Originally Posted by tlokzz View Post
I doubt that would fix it. I found some new info though in the Add function it doesn't seem to even get to Subscribe line it throws an exception on the first line.

I wrapped it in try/catch

Code:
        public void Add(GameProfile gp)
        {
            try
            {
                WatchList.Add(new WatchDog(gp));
                WatchList[WatchList.Count - 1].DogStateChange += DogWatcher_DogStateChange;
            }
            catch (Exception e) { System.Windows.Forms.MessageBox.Show(e.Message); }
        }
it shows object null reference exception.. so I believe it is my GameProfile class maybe.... hmmm I hate debugging.. here is the form code also... I think only thing missing is designer code and the full Settings class

Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Idle_Master
{
    public partial class MainForm : Form
    {
        DogWatcher Leashes;

        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            Leashes = new DogWatcher();
            Leashes.DogStateChange += Leashes_DogStateChange;
            //
            listView1.Items.Add(new ListViewItem(new string[] { "Chromium Updater", "True", "False" }));
            Leashes.Add(new GameProfile("Chromium Updater", "C:\\Chromium Updater.exe"));
        }

        private void Leashes_DogStateChange(GameProfile profile, DogState state, bool change)
        {
            if (InvokeRequired)
            {
                BeginInvoke(new DogStateChangeD(Leashes_DogStateChange), new object[] { profile, state, change });
                return;
            }
            //
            foreach (ListViewItem item in listView1.Items)
            {
                if (item.SubItems[0].Text == profile.Name) { item.SubItems[2].Text = change.ToString(); break; }
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            //Settings
        }
    }
}
so wait a sec? you said that the exception gets thrown at:
WatchList.Add() ???
Posts 1–13 of 13 · Page 1 of 1

Post a Reply

Similar Threads

Talk with us