如何处理触发事件中重叠的Console.Writeline()?

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

嘿,我正在为自己的Windows Server编写RDP Bruteforce Protection程序,甚至在更改RDP端口后也会受到攻击:/

但是我已经受登录控制台的困扰,当几乎同时发生2次攻击时,控制台输出“重叠”,如:

enter image description here

显示我基本操作的简约代码:

watcher.EventRecordWritten +=
                new EventHandler<EventRecordWrittenEventArgs>(EventLogEventRead);

public static async void EventLogEventRead(object obj,
        EventRecordWrittenEventArgs arg)
    {            
        if (arg.EventRecord != null)
        {
            string IP = GetIPFromRecord(arg.EventRecord)

            var json = await new HttpClient().GetStringAsync("https://api.ipgeolocationapi.com/geolocate/" + IP);
            var jsonDeserialized = new JavaScriptSerializer().Deserialize<dynamic>(json);
            string country = jsonDeserialized["name"];


            Console.WriteLine("IP:\t" + IP);
            Console.WriteLine("Country:\t" + country);
        }
        else
        {
            Console.WriteLine("The event instance was null.");
        }
    }

完整代码(无错误消息类):Pastebin

那么解决这种问题的最优雅的方法是什么?

c# events console-application overlapping console.writeline
2个回答
0
投票
它重叠是因为您为单个日志条目多次调用Console.WriteLine()。您需要准备整个输出主体并将其立即写入控制台。

0
投票
您应该使用锁:
© www.soinside.com 2019 - 2024. All rights reserved.