Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7801291
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 2, 20262026-06-02T00:54:04+00:00 2026-06-02T00:54:04+00:00

I want async write log in asp.net mvc,the code is like this: public ActionResult

  • 0

I want async write log in asp.net mvc,the code is like this:

public ActionResult Index()
        {
            byte[] buffer = Encoding.UTF8.GetBytes(string.Format("log:{0}{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff"), Environment.NewLine));
            FileStream fs = new FileStream(@"c:\log.txt", FileMode.Append, FileAccess.Write, FileShare.Write, 1024, true);
            fs.BeginWrite(buffer, 0, buffer.Length, ar =>
              {
                  fs.EndWrite(ar);
                  fs.Close();
              }, null);
         }

But the result is not I expected, some log not be recorded,can anyone tell me what’s wrong with the code

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-02T00:54:07+00:00Added an answer on June 2, 2026 at 12:54 am

    You need to ensure that only one thread is writing to the file. If you have 2 concurrent users calling the Index action at the same time chances are they will try to write to the log file at the same time and the second will fail. In a multithreaded applications such as ASP.NET always make sure that you are properly synchronizing access to shared resources.

    Also in your code you are not guarding against errors. What if an exception is thrown? You never close this stream and the second attempt to access it will throw an exception.

    So one possibility to simplify this code is to use the TPL:

    private static object _synRoot = new object();
    
    public ActionResult Index()
    {
        Task.Factory.StartNew(() =>
        {
            lock (_synRoot)
            {
                var data = string.Format("log:{0}{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff"), Environment.NewLine)
                System.IO.File.AppendAllText("log.txt", data);
            }
        });
        return View();
    }
    

    and to avoid such noise and pollution in your controllers you could use action filters:

    public class LogAttribute : ActionFilterAttribute
    {
        private static object _synRoot = new object();
    
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            Task.Factory.StartNew(() =>
            {
                lock (_synRoot)
                {
                    var data = string.Format("log:{0}{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff"), Environment.NewLine)
                    System.IO.File.AppendAllText(@"log.txt", data);
                }
            });
        }
    }
    

    and then:

    [Log]
    public ActionResult Index()
    {
        return View();
    }
    

    But instead of reinventing wheels I would recommend you using the tracing capabilities built into the .NET framework.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

In jQuery you can do : $(a[href$='.img']).each(function(index) { alert($(this).attr('href')); } I want to write
Want to do this: (EDIT: bad sample code, ignore and skip below) struct RECORD
I want to mimick this behavior: <script src=console.log.1.js></script> <script>console.log(2)</script> <script>console.log(3)</script> That logs out: 1
Some APIs, like the WebClient, use the Event-based Async pattern . While this looks
I am trying to work out how to use the new asp.net 4.5 async
I want to provide status updates during a long-running task on an ASP.NET WebForms
I'm using this code for reading socket_.async_read_some(boost::asio::buffer(data_, max_length), boost::bind(&session::handle_read, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); and this
Suppose you want to make an async request in JavaScript, but you want to
want to know why String behaves like value type while using ==. String s1
I want to create an async. server. i succeed to do that, but now

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.