static class 同时有这么多请求

static class with so many request at same time

我创建了一个静态ip和日志class。 ip class 找出用户的 ip 地址并记录 class 将其记录到一个文本文件中。 一切正常,但我想知道如果同时出现这么多请求会怎样? 我的意思是这两个 classes 都是静态的并且基于静态 classes 它会导致问题。 我该如何管理它们? 这是我的 ip class:

    public static class IP
    {
        public static string IP()
        {
            System.Web.HttpContext context = System.Web.HttpContext.Current;

            string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

            if (!string.IsNullOrEmpty(ipAddress))
            {
                string[] addresses = ipAddress.Split(',');
                if (addresses.Length != 0)
                {
                    return addresses[0];
                }
            }

            return context.Request.ServerVariables["REMOTE_ADDR"];
        }
    }
}

这里是我的日志 class 的一部分,它写入了文本文件:

        private static void WriteLine(string message)
    {
        string filePath = FilePath();
        CreateFile(filePath);
        try
        {
            using (StreamWriter log = File.AppendText(filePath))
                log.WriteLine(message);
        }
        catch (Exception)
        {
            //If can not access to file do nothing
            //throw;
        }
    }

它将正常工作,因为您没有任何 public 变量将保存在内存中并在每次 class 时更改已访问。

因此,随着方法的结束,您的变量的作用域也将结束。 但是如果是在内存中,就不会因为有多少用户同时使用而受到影响,不会乱七八糟。

由于您的 class 是静态的,因此您不会 运行 陷入争用问题。您的 IP.IP() 方法 class 是纯方法(即它不会更改任何状态)并且不包含任何锁,因此不会有任何争用。

您确实可能在 WriteLine 中遇到问题,因为您可能在执行工作时在同一线程上编写日志文件。这意味着文件写入充当锁定,因为在任何时候只能发生一次写入。

你想要的是记录到一个队列,然后在一个单独的线程上写那个队列;这是一个 classic 生产者-消费者模式。

或者,您可以避免重新发明轮子并使用现有的日志记录框架来为您处理这些事情,例如 log4net

Streamwriter 有一个默认的 4kb 缓冲区,如果需要可以根据定义修改:

public StreamWriter(
    Stream stream,
    Encoding encoding,
    int bufferSize
)

更有可能的是,您的计算机(包括磁盘访问)很可能比您的互联网访问快得多。