首页 > 解决方案 > 在其他代码运行时从函数返回响应 .netcore

问题描述

我有这个功能:

[HttpGet]
    [Route("See/{OID}")]
    public IActionResult See([FromRoute]long OID)
    {
        //time ham bayad chek bshe
        orders order = _context.orders.FirstOrDefault(e => e.OID == OID);

        lastViewed lv = _context.lastViewed.FirstOrDefault(e => e.UID.ToString() == User.Identity.Name);

        if (DateTime.Compare(lv.sentTime.AddSeconds(order.seconds), GetUTCDateTime()) < 0)
            return Content("1");

        unViewed UV = _context.unViewed.FirstOrDefault(e => e.UID.ToString() == User.Identity.Name && e.OID == OID);

        if (UV != null)            
            _context.unViewed.Remove(UV);            

        coins coin = _context.coins.FirstOrDefault(e => e.UID.ToString() == User.Identity.Name);            

        if (order.type > 50)
            coin.Coin += order.seconds * 8;
        else
            coin.Coin += order.seconds;

        order.view--;

        if (order.view == 0)
        {
            var uv = _context.unViewed.Where(e => e.OID == OID);
            foreach (unViewed uvv in uv)
                _context.unViewed.Remove(uvv);

            pastOrders po = new pastOrders
            {
                link = order.link,
                OID = order.OID,
                UID = order.UID
            };


            _context.pastOrders.Add(po);
            _context.orders.Remove(order);
        }
        _context.SaveChanges();
        return showlink();
    }

showlink() 函数是一个 IActionResult。showlink() 完全独立于其他代码。
我的问题是如何首先将 showlink() 响应给用户,然后在响应之后运行其他代码?
多谢。

标签: c#.net-core

解决方案


您可以安排其余代码在单独的线程上运行。但是请注意,这并不完全安全,因为您没有检查线程是否正确执行。为此,您需要在代码中添加其他检查以及在出现故障时收到通知的方法。采用异步模型是一项艰巨的任务,也是长期的解决方案。

但是,对于这种特殊情况,以下内容应该可以解除对您的阻止:

var result = showlink();
Task.Factory.StartNew(() => {
    // Rest of your code that needs to run in the background.
});
return result;

推荐阅读