码迷,mamicode.com
首页 > 其他好文 > 详细

异步方法测试,暂时不知道对错

时间:2021-02-15 12:42:07      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:art   ali   setting   eric   nta   space   com   action   sel   

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Data.SqlClient;
using System.Threading;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private async void button1_Click(object sender, EventArgs e)
{

textBox1.Text += "Main Start" + Thread.CurrentThread.ManagedThreadId.ToString()+"\r\n";
DoAction("http://www.jsglobalacademy.org/About_School.html", "");
textBox1.Text += "Main End" + Thread.CurrentThread.ManagedThreadId.ToString() + "\r\n";

}

 


public async Task DoAction(string url, string xml)
{
textBox1.Text += "DoAction Start" + Thread.CurrentThread.ManagedThreadId.ToString() + "\r\n";

await SendPostHttpRequest(url, "application/x-www-form-urlencoded", "{}");
textBox1.Text += "DoAction End" + Thread.CurrentThread.ManagedThreadId.ToString() + "\r\n";

}

 


public async Task<WebResponse> SendPostHttpRequest(string url, string contentType, string requestData)
{

textBox1.Text += "Request Start" + Thread.CurrentThread.ManagedThreadId.ToString() + "\r\n";
WebRequest request = (WebRequest)HttpWebRequest.Create(url);
request.Method = "POST";
request.ContentType = contentType;
request.Headers.Set("Pragma", "no-cache");

byte[] postBytes = null;
postBytes = Encoding.UTF8.GetBytes(requestData);
request.ContentLength = postBytes.Length;


using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(postBytes, 0, postBytes.Length);
}


string result = string.Empty;
WebResponse ws = await request.GetResponseAsync();


textBox1.Text += "Request End " + Thread.CurrentThread.ManagedThreadId.ToString() + "\r\n";
ExeDb(" select * from book_categories ");

return ws;

 

}

 

public async Task ExeDb(string sql)
{

textBox1.Text += "Db Start" + Thread.CurrentThread.ManagedThreadId.ToString() + "\r\n";
SqlConnection Conn = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["db"]);
SqlCommand cmd = new SqlCommand(sql, Conn);
await Conn.OpenAsync();
await cmd.ExecuteNonQueryAsync().ContinueWith(_ => Conn.Close());

textBox1.Text += "Db End" + Thread.CurrentThread.ManagedThreadId.ToString() + "\r\n";
}


}
}

异步方法测试,暂时不知道对错

标签:art   ali   setting   eric   nta   space   com   action   sel   

原文地址:https://www.cnblogs.com/mqingqing123/p/14398205.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!