消息记录类的问题 - 在主窗体之外触发时类不处理事件

问题描述 投票:0回答:1

我创建了一个类

Logging
,其中事件
Logging.Send()
触发一个事件,该事件将字符串
message
传递给任何订阅的类。

在本例中,我使用此方法

Logging.Send(string message, ELogType type);
触发事件
Logs
,然后由我的主
Form
监听,它将消息附加到充当我的文本日志的
RichTextBox
,具体取决于消息的类型。

我的主要问题是,此 Logging.Send 方法仅在我的主 Form 类中调用时将其消息发送到日志。如果我在另一个类中调用它,为了示例起见,我们将其称为

Controller
,它会触发事件,但订阅表单似乎没有收到它。做错了什么?

这是我的问题的示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

public enum ELogType { Primary, Simple, Extra, Readout, Debug }

public class Logging
{

    public Logging() { }

    public event EventHandler<LoggerMessageArgs> Log;

    public bool PostPrimaryLogs = true,
        PostSimpleLogs = true,
        PostExtraLogs = false,
        PostReadoutLogs = false,
        PostDebugLogs = false;

    public void Send(string message)
    {
        Send(message, ELogType.Primary);
    }

    public void Send(string primaryMessage, string simpleMessage)
    {
        Send(new[] { primaryMessage, simpleMessage }, new[] { ELogType.Primary, ELogType.Simple });
    }

    public void Send(string message, ELogType type)
    {
        Console.WriteLine("sendtest"); //to check that the send event was happening.
        if ((type == ELogType.Primary && PostPrimaryLogs == true) //is there some way to avoid this giant if statement here?
        || (type == ELogType.Simple && PostSimpleLogs == true)
        || (type == ELogType.Extra && PostExtraLogs == true)
        || (type == ELogType.Readout && PostReadoutLogs == true)
        || (type == ELogType.Debug && PostDebugLogs == true))
        Log?.Invoke(this, new LoggerMessageArgs(message, type));
    }

    public void Send(string[] messages, ELogType[] types) 
    {
        if (messages.Length == types.Length)

        for (int i = 0; i < messages.Length; i++) 
        {
                Send(messages[i], types[i]);
        }
    }
}

public class LoggerMessageArgs
{
    public string Message { get; }

    public ELogType LogType { get; }

    public LoggerMessageArgs(string message)
    {
        Message = message;
        LogType = ELogType.Primary;
    }

    public LoggerMessageArgs(string message, ELogType logType)
    {
        Message = message;
        LogType = logType;
    }
}

public class Controller
{
    Logging Logger = new Logging();

    public async Task DoControl()
    {
        Logger.Send("beginning doControl", ELogType.Primary);
        await Task.Delay(1000); //do work
        Logger.Send("finished doControl", ELogType.Primary);
        return Task.CompletedTask;
    }
}

public partial class Form1: Form
{
    Logging Logger = new Logging();

    //needs an additional RichTextBox LogTextBox, and a RichTextBox SimpleLogTextBox. The simple log box isn't super important to the issue at hand. It's mostly used as a status indicator.

    Form1()
    {
        InitializeComponent();
        Logger.Log += (sender, e) => 
        {
            Action action = () =>
            {
                if (e.LogType == ELogType.Primary || e.LogType == ELogType.Debug || e.LogType == ELogType.Extra || e.LogType == ELogType.Readout)
                {
                    LogTextBox.AppendText($@"{DateTime.Now:hh\:mm\:ss\.ffff}: {e.Message}{Environment.NewLine}");
                    LogTextBox.SelectionStart = LogTextBox.Text.Length;
                    LogTextBox.ScrollToCaret();
                }
                if (e.LogType == ELogType.Simple)
                {
                    SimpleLogTextBox.AppendText($@"{e.Message}{Environment.NewLine}");
                    SimpleLogTextBox.SelectionStart = SimpleLogTextBox.Text.Length;
                    SimpleLogTextBox.ScrollToCaret();
                }
            };

            if (LogTextBox.InvokeRequired)
            {
                LogTextBox.Invoke(action);
            }

            else
            {
                action();
            }
        };
    }

    private void TestButton_Click(object sender, EventArgs e)
    {
        Logger.Send(new string[] { "Form Primary Log Test", "Form Simple Log Test" }, new ELogType[] { ELogType.Primary, ELogType.Simple }); //logs come back from this one
        Controller.DoControl() //no logs come back from this one.        
    }
}        

使用此代码,我在主日志中获取字符串“{datetime} Form Primary Test Log”,但从 DoControl 获得完全无线电静默。

我该如何解决这个问题?

谢谢你。

c# class events
1个回答
0
投票

使您的事件静态,以便即使您创建多个记录器实例,该事件也只有一个实例。

public static event EventHandler<LoggerMessageArgs> Log;
© www.soinside.com 2019 - 2024. All rights reserved.