其他分享
首页 > 其他分享> > 异步方法测试,暂时不知道对错

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

作者:互联网

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";
}


}
}

标签:异步,string,Thread,Text,System,对错,ToString,测试,using
来源: https://www.cnblogs.com/mqingqing123/p/14398205.html