Table of Contents
[WPF MaterialDesign sample open source project] Work Time Manager
[.net] Create your own log component - improved version
Home Backend Development C#.Net Tutorial Introduction to WPF MaterialDesign sample open source project

Introduction to WPF MaterialDesign sample open source project

Jun 23, 2017 pm 03:01 PM
manager time Open source project

Hello all, I’m back again

This time we really started to talk about the development ideas of small but useful modules or components in open source projects .

At the same time, the software has been updated to version 1.60, which supports new user registration, and you can no longer use a unified test account.

You can download it through the following path:

1. Fellow the project on GitHub, download it locally, and generate it to get the latest version of the program.

2. Users whose local version is beta v0.5 can directly click Update in the upper right corner of the program

3. The last compressed package for non-Microsoft developers is the following compressed package, which can be directly decompressed. be usable.


If you still don’t know what the software is, you can check out this blog post:

[WPF MaterialDesign sample open source project] Work Time Manager

Today, let’s talk about the client’s log component.

I don’t know if components are appropriate. Anyway, they are small modules that are part of the software and can be reused. I call them components.

This time the log class is a very typical component. The log has many characteristics;

1. It will be used anywhere in the software.

2. It will be used at any time. Being called

3, extremely high usage

4, frequent io operations

When I just came into contact with c# I had used Log4net when I was a child, but the idea that came to my mind at that time was that my program might only be a few meters in size, and a log component would be bigger than my main program. This was obviously inappropriate.

So before I graduated two years ago, I started making my first log component.

[.net] Create your own log component - improved version

The basic idea is still good, including: threads, blocking, resource competition, etc. have been taken into consideration.

As the saying goes, a newborn calf is not afraid of tigers, so he just started doing it without knowing anything.

Written the first version of the log component by opening threads.

However, after all, he is young, and the problem is still obvious. Typing 100 messages in one second will not work.

So when I started C# development again, I took some time to refactor.

First, let’s start with the overall architecture:
- Features of old components:
* Use Multi-thread queue, using mutually exclusive variables to control thread writing of text.
* Control the contention of resources through singleton locking
* Threads are randomly selected to lock, and the log time sequence of writing is May be wrong
* One thread operates one text operation, switches are operated in one thread, and only one variable is written at a time
- Advantages:
* Multi-threaded operation, superficially improving operation efficiency
* Single instance locking to ensure uniqueness
- Disadvantages:
* Low performance, excessive operation of io Leading to severe redundancy in performance
* Only write one item at a time
-Improvement
* Use the producer-consumer model, separate operations, and limit the number of threads
* Use stack queue, first in, first out, to ensure log order
* Single instance IO variable, batch write operations
Transformation results:
using System;using System.Collections;using System.IO;using System.Text;using System.Threading;using System.Windows.Threading;namespace Helper
{public static class LogHelper
    {private static readonly Queue LogQueue = new Queue();private static bool _isStreamClose = true;private static bool _isThreadBegin = false;private static StreamWriter _fileStreamWriter;private static readonly string fileName =@"BugLog.txt";static int _intervalTime = 10000;// 10sstatic System.Timers.Timer _timer = new System.Timers.Timer(_intervalTime);/// <summary>/// 添加日志队列/// </summary>/// <param name="message"></param>public static void AddLog(string message)
        {string logContent = $"[{DateTime.Now:yyyy-MM-dd hh:mm:ss}] =>{message}";
            LogQueue.Enqueue(logContent);if (!_isThreadBegin)
            {
                BeginThread();
            }
        }public static void AddLog(Exception ex)
        {var logContent = $"[{DateTime.Now:yyyy-MM-dd hh:mm:ss}]错误发生在:{ex.Source},\r\n 内容:{ex.Message}";
            logContent += $"\r\n  跟踪:{ex.StackTrace}";
            LogQueue.Enqueue(logContent);if (!_isThreadBegin)
            {
                BeginThread();
            }
        }/// <summary>/// 读取日志队列的一条数据/// </summary>/// <returns></returns>private static object GetLog()
        {return LogQueue.Dequeue();
        }/// <summary>/// 开启定时查询线程/// </summary>public static void BeginThread()
        {
            _isThreadBegin = true;//实例化Timer类,设置间隔时间为10000毫秒;     _timer.Interval = _intervalTime;

            _timer.Elapsed += SetLog;//到达时间的时候执行事件;   _timer.AutoReset = true;//设置是执行一次(false)还是一直执行(true);     _timer.Enabled = true;
        }/// <summary>/// 写入日志/// </summary>private static void SetLog(object source, System.Timers.ElapsedEventArgs e)
        {if (LogQueue.Count == 0)
            {if (_isStreamClose) return;
                _fileStreamWriter.Flush();
                _fileStreamWriter.Close();
                _isStreamClose = true;return;
            }if (_isStreamClose)
            {
                Isexist();string errLogFilePath = Environment.CurrentDirectory + @"\Log\" + fileName.Trim();if (!File.Exists(errLogFilePath))
                {
                    FileStream fs1 = new FileStream(errLogFilePath, FileMode.Create, FileAccess.Write);
                    _fileStreamWriter = new StreamWriter(fs1);
                }else{
                    _fileStreamWriter = new StreamWriter(errLogFilePath, true);
                }
                _isStreamClose = false;
            }var strLog = new StringBuilder();var onceTime = 50;var lineNum = LogQueue.Count > onceTime ? onceTime : LogQueue.Count;for (var i = 0; i < lineNum; i++)
            {
                strLog.AppendLine(GetLog().ToString());
            }

            _fileStreamWriter.WriteLine(strLog.ToString());

        }/// <summary>/// 判断是否存在日志文件/// </summary>private static void Isexist()
        {string path = Environment.CurrentDirectory + @"\Log\";if (!File.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
        }
    }
}
Copy after login

The code does not have the application of third-party components, just copy this file and use it.

We have not dealt with some special situations for the time being, such as log files being occupied, temporary software shutdown, and considerations such as queue trigger time and batch write number. This is just a basic demo,

Of course, if you want to know about subsequent improvements, you can follow the project's GitHub.

Of course, I look forward to your better suggestions. Let’s learn together. If you have a good idea but don’t want to write it yourself, I’ll help you realize it!


The above is the detailed content of Introduction to WPF MaterialDesign sample open source project. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Ten recommended open source free text annotation tools Ten recommended open source free text annotation tools Mar 26, 2024 pm 08:20 PM

Text annotation is the work of corresponding labels or tags to specific content in text. Its main purpose is to provide additional information to the text for deeper analysis and processing, especially in the field of artificial intelligence. Text annotation is crucial for supervised machine learning tasks in artificial intelligence applications. It is used to train AI models to help more accurately understand natural language text information and improve the performance of tasks such as text classification, sentiment analysis, and language translation. Through text annotation, we can teach AI models to recognize entities in text, understand context, and make accurate predictions when new similar data appears. This article mainly recommends some better open source text annotation tools. 1.LabelStudiohttps://github.com/Hu

15 recommended open source free image annotation tools 15 recommended open source free image annotation tools Mar 28, 2024 pm 01:21 PM

Image annotation is the process of associating labels or descriptive information with images to give deeper meaning and explanation to the image content. This process is critical to machine learning, which helps train vision models to more accurately identify individual elements in images. By adding annotations to images, the computer can understand the semantics and context behind the images, thereby improving the ability to understand and analyze the image content. Image annotation has a wide range of applications, covering many fields, such as computer vision, natural language processing, and graph vision models. It has a wide range of applications, such as assisting vehicles in identifying obstacles on the road, and helping in the detection and diagnosis of diseases through medical image recognition. . This article mainly recommends some better open source and free image annotation tools. 1.Makesens

Can AI conquer Fermat's last theorem? Mathematician gave up 5 years of his career to turn 100 pages of proof into code Can AI conquer Fermat's last theorem? Mathematician gave up 5 years of his career to turn 100 pages of proof into code Apr 09, 2024 pm 03:20 PM

Fermat's last theorem, about to be conquered by AI? And the most meaningful part of the whole thing is that Fermat’s Last Theorem, which AI is about to solve, is precisely to prove that AI is useless. Once upon a time, mathematics belonged to the realm of pure human intelligence; now, this territory is being deciphered and trampled by advanced algorithms. Image Fermat's Last Theorem is a "notorious" puzzle that has puzzled mathematicians for centuries. It was proven in 1993, and now mathematicians have a big plan: to recreate the proof using computers. They hope that any logical errors in this version of the proof can be checked by a computer. Project address: https://github.com/riccardobrasca/flt

A closer look at PyCharm: a quick way to delete projects A closer look at PyCharm: a quick way to delete projects Feb 26, 2024 pm 04:21 PM

Title: Learn more about PyCharm: An efficient way to delete projects. In recent years, Python, as a powerful and flexible programming language, has been favored by more and more developers. In the development of Python projects, it is crucial to choose an efficient integrated development environment. As a powerful integrated development environment, PyCharm provides Python developers with many convenient functions and tools, including deleting project directories quickly and efficiently. The following will focus on how to use delete in PyCharm

PyCharm Practical Tips: Convert Project to Executable EXE File PyCharm Practical Tips: Convert Project to Executable EXE File Feb 23, 2024 am 09:33 AM

PyCharm is a powerful Python integrated development environment that provides a wealth of development tools and environment configurations, allowing developers to write and debug code more efficiently. In the process of using PyCharm for Python project development, sometimes we need to package the project into an executable EXE file to run on a computer that does not have a Python environment installed. This article will introduce how to use PyCharm to convert a project into an executable EXE file, and give specific code examples. head

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

Alibaba 7B multi-modal document understanding large model wins new SOTA Alibaba 7B multi-modal document understanding large model wins new SOTA Apr 02, 2024 am 11:31 AM

New SOTA for multimodal document understanding capabilities! Alibaba's mPLUG team released the latest open source work mPLUG-DocOwl1.5, which proposed a series of solutions to address the four major challenges of high-resolution image text recognition, general document structure understanding, instruction following, and introduction of external knowledge. Without further ado, let’s look at the effects first. One-click recognition and conversion of charts with complex structures into Markdown format: Charts of different styles are available: More detailed text recognition and positioning can also be easily handled: Detailed explanations of document understanding can also be given: You know, "Document Understanding" is currently An important scenario for the implementation of large language models. There are many products on the market to assist document reading. Some of them mainly use OCR systems for text recognition and cooperate with LLM for text processing.

Just released! An open source model for generating anime-style images with one click Just released! An open source model for generating anime-style images with one click Apr 08, 2024 pm 06:01 PM

Let me introduce to you the latest AIGC open source project-AnimagineXL3.1. This project is the latest iteration of the anime-themed text-to-image model, aiming to provide users with a more optimized and powerful anime image generation experience. In AnimagineXL3.1, the development team focused on optimizing several key aspects to ensure that the model reaches new heights in performance and functionality. First, they expanded the training data to include not only game character data from previous versions, but also data from many other well-known anime series into the training set. This move enriches the model's knowledge base, allowing it to more fully understand various anime styles and characters. AnimagineXL3.1 introduces a new set of special tags and aesthetics

See all articles