在NET+EF+MVC开发接口时,有些任务需要异步执行,下面笔者介绍一下异步调用的方法,以供参考:
#region 记录机器人心跳
[HttpPost]
public async Task AddHeartBeat(decimal KindergartenID, decimal host_id, string longitude_latitude, string map_location, short run_state, string device_name, string equipment_number, string serverurl,string createtime=null)
{
var task = Task.Run(() =>
{
if (KindergartenID > 0 && host_id > 0)
{
string ip = "";
try
{
if(string.IsNullOrEmpty(createtime))
{
createtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
}
#region 提交到api服务器
var postUrl = serverurl + "/api/HXBY_bbwhost/Addnetmonitor";
WebRequest request7 = WebRequest.Create(postUrl);
request7.Method = "POST";
//post传参数
string postdata = "longitude_latitude=" + longitude_latitude + "&host_id=" + host_id + "&KindergartenID=" + KindergartenID + "&map_location=" + Server.UrlEncode(map_location) + "&run_state=" + run_state + "&device_name=" + Server.UrlEncode(device_name) + "&equipment_number=" + equipment_number + "&ip=" + ip;
byte[] bytes = Encoding.ASCII.GetBytes(postdata);
request7.Timeout = 5000;
request7.ContentType = "application/x-www-form-urlencoded";
request7.ContentLength = postdata.Length;
Stream sendStream = request7.GetRequestStream();
sendStream.Write(bytes, 0, bytes.Length);
sendStream.Close();
#endregion
#region 主机心跳
//0:根据经纬度记录 1:根据IP记录
int type = 0;
string longitude = null;
string latitude = null;
if (!string.IsNullOrEmpty(longitude_latitude))
{
string[] array = longitude_latitude.Split('|');
if (array.Length == 2)
{
type = 0;
longitude = array[0];
latitude = array[1];
}
}
else
{
type = 1;
longitude = "";
latitude = "";
map_location = WisdomStarts.Common.Utils.GetIPArea(ip);
}
DBHelper dd = new DBHelper();
int rows = dd.Set("insert into hx_hw_netmonitor( KindergartenID,host_id,longitude,latitude,map_location,run_state,device_name,equipment_number,ip,type,iswarning,createtime,serverurl ) values('" + KindergartenID + "', '" + host_id + "','" + longitude + "' ,'" + latitude + "' ,'" + map_location + "'," + run_state + ",'" + device_name + "','" + equipment_number + "','" + ip + "' ," + type + ",0,'" + createtime + "','" + serverurl + "' ) ");
#endregion 机器人心跳
}
catch (Exception ee)
{
WisdomStarts.Common.Log.NetLog.WriteTextLog("记录晨检机接送机心跳", ee.ToString());
}
}
});
await task;
}
#endregion
留言与评论(共有 0 条评论) “” |