Alternative solution to HostingEnvironment.QueueBackgroundWorkItem in .NET Core

后端 未结 6 1852
栀梦
栀梦 2020-12-23 11:04

We are working with .NET Core Web Api, and looking for a lightweight solution to log requests with variable intensity into database, but don\'t want client\'s to wait for th

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-23 11:43

    The original HostingEnvironment.QueueBackgroundWorkItem was a one-liner and very convenient to use. The "new" way of doing this in ASP Core 2.x requires reading pages of cryptic documentation and writing considerable amount of code.

    To avoid this you can use the following alternative method

        public static ConcurrentBag bs = new ConcurrentBag();
    
        [HttpPost("/save")]
        public async Task SaveAsync(dynamic postData)
        {
    
        var id = (String)postData.id;
    
        Task.Run(() =>
                    {
                        bs.Add(Create(id));
                    });
    
         return new OkResult();
    
        }
    
    
        private Boolean Create(String id)
        {
          /// do work
          return true;
        }
    

    The static ConcurrentBag bs will hold a reference to the object, this will prevent garbage collector from collecting the task after the controller returns.

提交回复
热议问题