先看以下代码
using System;
using System.Data;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using WebSite.Common;
using WebSite.DBUtility;
/// <summary>
/// ProViewService 的摘要说明
/// </summary>
public class ProViewService : System.Web.HttpTaskAsyncHandler
{
public ProViewService()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
public static async Task BrowseCount(HttpContext c, int id)
{
//获取产品原来的浏览量
await Task.Delay(1000);
JsonResult.error(c, "进入11异步拉!");
DataSet set2 = new DataSet();
set2 = DbHelperSQL.Query("select BrowseCount FROM SW_Product where ID=10001");
DataTable tb = set2.Tables[0];
int Browse = 1;
if (tb.Rows[0]["BrowseCount"].ToString() != "")
{
Browse = Convert.ToInt32(tb.Rows[0]["BrowseCount"].ToString()) + 1;
}
DbHelperSQL.Query("update SW_Product set BrowseCount = " + Browse + " where ID = " + id + "");
JsonResult.error(c, "111异步完成啦!!");
}
public static void ProIDAsync(HttpContext c,int ID,int WebSiteID)
{
if (ID == 0)
{
JsonResult.error(c, "您要查询的产品不存在!");
};
try
{
Task.Run(async () =>
{
JsonResult.error(c, "开始异步调用拉!");
//更新产品访问流量
await BrowseCount(c,ID);
});
JsonResult.error(c, "异步调完用拉!");
string strWhere = "p.TypeID=pt.ID and p.ID=" + ID + " and p.State=1 ";
StringBuilder strSql = new StringBuilder();
strSql.Append("select p.ID,p.Content1 Content,p.PicThumbnail,p.TypeID ");
if (WebSiteID == 10002)
{
strSql.Append(",pt.IncludeType TypeName,p.Other1 ProductName");
}
else
{
strSql.Append(",pt.Title TypeName,p.ProductName");
}
strSql.Append(" from dbo.SW_Product p,dbo.SW_ProductType pt ");
strSql.Append(" where " + strWhere + " ORDER BY p.OrderBy,p.AddDate");
JsonResult.error(c, "开启去执行sql拉!");
JsonResult.OK(c, strSql.ToString(), 1);
JsonResult.error(c, "全部执行完毕!");
}
catch (System.Exception)
{
JsonResult.error(c);
}
}
public override Task ProcessRequestAsync(HttpContext context)
{
throw new NotImplementedException();
}
}
直接调用这个方法: BrowseCount(c, ID); 会导致程序崩溃。
用我们上面的方法:
Task.Run(async () =>
{
JsonResult.error(c, "开始异步调用拉!");
//更新产品访问流量
await BrowseCount(c,ID);
});
调试后会得到以下结果:
{"code":500,"data":"异步调完用拉!"}
{"code":500,"data":"开启去执行sql拉!"}
{"code":500,"data":"开始异步调用拉!"}
{"code":200,"data":{"ID":10001,"Content":null,"PicThumbnail":"/UserFiles/upload/image/20191226/20191226154159829_t.JPG","TypeID":10568,"TypeName":"环装","ProductName":""}}{"code":500,"data":"全部执行完毕!"}
按照网上的使用 await BrowseCount(c, ID);这个方法也是跟第一种方法一样,直接停止工作。
最后选择了第二种,具体原因暂时还搞不懂,有时间研究好后再跟大家一起分享!