Home > Software engineering >  Outlook ItemAdd event not work constantly
Outlook ItemAdd event not work constantly

Time:10-25

I have a tiny C# program which listen to the outlook with ItemAdd event, every time I start the program, it will mulfunction after a few days run, for example I start the program on Monday, it will be failure on Thursday, or Wednesday, then it has to be restarted.
What's going on behind the scene? And how to fix it?
This should not be RAM issue? Because I have 32G RAM.
Win10 21H1, Outlook 2016, .net framework 4.7.2

public partial class Form2 : Form
{
    private NameSpace _ns;
    private readonly ApplicationClass _outlook = new ApplicationClass();
    private readonly StringProcessor _processor = new StringProcessor();
    private Items _items;

    public Form2()
    {
        InitializeComponent();
    }

    private void Form2_Load(object sender, EventArgs e)
    {
        try
        {
            Main();
        }
        catch (System.Exception ex)
        {
        }
    }

    private void Main()
    {
        try
        {
            _ns = _outlook.GetNamespace("MAPI");
            MAPIFolder myFolder;

            if (Environment.UserName == XmlService.UserName)
            {
                var box = XmlService.Inbox;
                myFolder = GetFolderItem(box);
            }
            else
            {
                myFolder = _ns.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
            }

            if (myFolder != null)
            {
                _items = myFolder.Items;
                _items.ItemAdd  = Items_ItemAdd;
            }
            else
            {
                Loger.PrintLog("Can not get folder");
            }
        }
        catch (System.Exception e)
        {
            Loger.PrintLog(e.Message);
        }
    }

    private void Items_ItemAdd(object item)
    {}
}

CodePudding user response:

Keep in mind that folder based events in Outlook were only designed for the UI purposes. The events can be dropped under heavy loads; they can also be disconnected if there was an RPC failure, especially in the online (as opposed to cached) mode.

The events should at best be a hint that you code that processes new events needs to run sooner rather than later.

CodePudding user response:

it will mulfunction after a few days run

Most probably the Outlook process was closed automatically. Try to create an Outlook window by using the Explorers.Add or Inspectors.Add method which creates a new instance of the explorer or inspector window and keep them alive in the code like you do for the Items collection. Note, without calling the Display method any Outlook UI will not be visible.

  • Related