Winforms 具有取消支持(CancellationTokenSource)和进度报告的PostSubmitter异步CTP
各位开发人员 我有一个课程,可以使用帖子或获取并阅读回复发布到网站。它现在都是异步的,不会导致UI挂起 我现在需要升级以处理取消。正在使用的所有异步方法都不接受取消令牌。我需要了解为什么以及我的选择是什么。如果可能,我应该在类中创建CancellationTokenSource对象还是从UI将其参数化 其次,我需要公开PostData()方法的进度。我该怎么做 班级:Winforms 具有取消支持(CancellationTokenSource)和进度报告的PostSubmitter异步CTP,winforms,c#-4.0,asynchronous,async-await,Winforms,C# 4.0,Asynchronous,Async Await,各位开发人员 我有一个课程,可以使用帖子或获取并阅读回复发布到网站。它现在都是异步的,不会导致UI挂起 我现在需要升级以处理取消。正在使用的所有异步方法都不接受取消令牌。我需要了解为什么以及我的选择是什么。如果可能,我应该在类中创建CancellationTokenSource对象还是从UI将其参数化 其次,我需要公开PostData()方法的进度。我该怎么做 班级: using System; using System.Collections.Specialized; using System
using System;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Forms;
using System.Collections.Generic;
using RESTClient.Core.UploadFile;
using System.Threading;
namespace RESTClient.Core {
/// <summary>
/// Submits post data to a url.
/// </summary>
public class PostSubmitter {
#region Backing Store
private string _URL = string.Empty;
private NameValueCollection _PostValues = new NameValueCollection();
private PostTypeEnum _PostType = PostTypeEnum.GET;
#endregion
#region Constructors
/// <summary>
/// Default constructor.
/// </summary>
public PostSubmitter() {
}
/// <summary>
/// Constructor that accepts a url as a parameter
/// </summary>
/// <param name="url">The url where the post will be submitted to.</param>
public PostSubmitter(string url)
: this() {
_URL = url;
}
/// <summary>
/// Constructor allowing the setting of the url and items to post.
/// </summary>
/// <param name="url">the url for the post.</param>
/// <param name="values">The values for the post.</param>
public PostSubmitter(string url, NameValueCollection values)
: this(url) {
_PostValues = values;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the url to submit the post to.
/// </summary>
public string Url {
get {
return _URL;
}
set {
_URL = value;
}
}
/// <summary>
/// Gets or sets the name value collection of items to post.
/// </summary>
public NameValueCollection PostItems {
get {
return _PostValues;
}
set {
_PostValues = value;
}
}
/// <summary>
/// Gets or sets the type of action to perform against the url.
/// </summary>
public PostTypeEnum Type {
get {
return _PostType;
}
set {
_PostType = value;
}
}
#endregion
/// <summary>
/// Posts the supplied data to specified url.
/// </summary>
/// <returns>a string containing the result of the post.</returns>
public async Task<String> Post() {
StringBuilder parameters = new StringBuilder();
for (int i = 0; i < _PostValues.Count; i++) {
EncodeAndAddItem(ref parameters, _PostValues.GetKey(i), _PostValues[i]);
}
string result = await PostData(_URL, parameters.ToString());
return result;
}
/// <summary>
/// Posts the supplied data to specified url.
/// </summary>
/// <param name="url">The url to post to.</param>
/// <returns>a string containing the result of the post.</returns>
public async Task<String> Post(string url) {
_URL = url;
return await this.Post();
}
/// <summary>
/// Posts the supplied data to specified url.
/// </summary>
/// <param name="url">The url to post to.</param>
/// <param name="values">The values to post.</param>
/// <returns>a string containing the result of the post.</returns>
public async Task<String> Post(string url, NameValueCollection values) {
_PostValues = values;
return await this.Post(url);
}
/// <summary>
/// Posts data to a specified url. Note that this assumes that you have already url encoded the post data.
/// </summary>
/// <param name="postData">The data to post.</param>
/// <param name="url">the url to post to.</param>
/// <returns>Returns the result of the post.</returns>
private async Task<String> PostData(string url, string postData) {
HttpWebRequest request = null;
if (_PostType == PostTypeEnum.POST) {
Uri uri = new Uri(url);
request = WebRequest.Create(uri) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postData.Length;
using (Stream writeStream = await request.GetRequestStreamAsync()) {
UTF8Encoding encoding = new UTF8Encoding();
byte[] bytes = encoding.GetBytes(postData);
writeStream.Write(bytes, 0, bytes.Length);
}
}
else {
Uri uri = new Uri(url + "?" + postData);
request = WebRequest.Create(uri) as HttpWebRequest;
request.Method = "GET";
}
using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync()) {
using (Stream responseStream = response.GetResponseStream()) {
using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8)) {
return await readStream.ReadToEndAsync();
}
}
}
}
/// <summary>
/// Encodes an item and ads it to the string.
/// </summary>
/// <param name="baseRequest">The previously encoded data.</param>
/// <param name="dataItem">The data to encode.</param>
/// <returns>A string containing the old data and the previously encoded data.</returns>
private void EncodeAndAddItem(ref StringBuilder baseRequest, string key, string dataItem) {
if (baseRequest == null) {
baseRequest = new StringBuilder();
}
if (baseRequest.Length != 0) {
baseRequest.Append("&");
}
baseRequest.Append(key);
baseRequest.Append("=");
baseRequest.Append(HttpUtility.UrlEncode(dataItem));
}
public async void HttpUploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc) {
//log.Debug(string.Format("Uploading {0} to {1}", file, url));
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
HttpWebRequest wr = WebRequest.Create(url) as HttpWebRequest;
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
wr.KeepAlive = true;
wr.Credentials = CredentialCache.DefaultCredentials;
Stream rs = await wr.GetRequestStreamAsync();
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
foreach (string key in nvc.Keys) {
await rs.WriteAsync(boundarybytes, 0, boundarybytes.Length);
string formitem = string.Format(formdataTemplate, key, nvc[key]);
byte[] formitembytes = Encoding.UTF8.GetBytes(formitem);
await rs.WriteAsync(formitembytes, 0, formitembytes.Length);
}
await rs.WriteAsync(boundarybytes, 0, boundarybytes.Length);
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(headerTemplate, paramName, file, contentType);
byte[] headerbytes = Encoding.UTF8.GetBytes(header);
rs.WriteAsync(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = await fileStream.ReadAsync(buffer, 0, buffer.Length)) != 0) {
await rs.WriteAsync(buffer, 0, bytesRead);
}
fileStream.Close();
byte[] trailer = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
await rs.WriteAsync(trailer, 0, trailer.Length);
rs.Close();
WebResponse wresp = null;
try {
wresp = await wr.GetResponseAsync();
Stream stream2 = wresp.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
//log.Debug(string.Format("File uploaded, server response is: {0}", reader2.ReadToEnd()));
}
catch (Exception ex) {
//log.Error("Error uploading file", ex);
if (wresp != null) {
wresp.Close();
wresp = null;
}
}
finally {
wr = null;
}
/**
NameValueCollection nvc = new NameValueCollection();
nvc.Add("id", "TTR");
nvc.Add("btn-submit-photo", "Upload");
HttpUploadFile("http://your.server.com/upload", @"C:\test\test.jpg", "file", "image/jpeg", nvc);
**/
}
public async Task<String> ExecutePostRequest(Uri url, Dictionary<string, string> postData, FileInfo fileToUpload, string fileMimeType, string fileFormKey) {
HttpWebRequest request = WebRequest.Create(url.AbsoluteUri) as HttpWebRequest;
request.Method = "POST";
request.KeepAlive = true;
String boundary = Utility.CreateFormDataBoundary();
request.ContentType = "multipart/form-data; boundary=" + boundary;
Stream requestStream = await request.GetRequestStreamAsync();
postData.WriteMultipartFormData(requestStream, boundary);
if (fileToUpload != null) {
//TODO: Need async here...
fileToUpload.WriteMultipartFormData(requestStream, boundary, fileMimeType, fileFormKey);
}
byte[] endBytes = Encoding.UTF8.GetBytes("--" + boundary + "--");
await requestStream.WriteAsync(endBytes, 0, endBytes.Length);
requestStream.Close();
using (WebResponse response = await request.GetResponseAsync()) {
using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
return await reader.ReadToEndAsync();
}
}
}
}
}
使用系统;
使用System.Collections.Specialized;
使用System.IO;
Net系统;
使用系统文本;
使用System.Threading.Tasks;
使用System.Web;
使用System.Windows.Forms;
使用System.Collections.Generic;
使用RESTClient.Core.UploadFile;
使用系统线程;
命名空间RESTClient.Core{
///
///将post数据提交到url。
///
公共类提交人{
#地区后备商店
私有字符串_URL=string.Empty;
私有NameValueCollection_PostValues=新的NameValueCollection();
私有PostTypeEnum _PostType=PostTypeEnum.GET;
#端区
#区域构造函数
///
///默认构造函数。
///
公共后提交者(){
}
///
///接受url作为参数的构造函数
///
///文章将提交到的url。
公共PostSubmiter(字符串url)
:此(){
_URL=URL;
}
///
///构造函数,允许设置要发布的url和项目。
///
///文章的url。
///该帖子的值。
公共PostSubmiter(字符串url、NameValueCollection值)
:此(url){
_PostValues=值;
}
#端区
#区域属性
///
///获取或设置要将文章提交到的url。
///
公共字符串Url{
得到{
返回URL;
}
设置{
_URL=值;
}
}
///
///获取或设置要发布的项的名称值集合。
///
public NameValueCollection positems{
得到{
返回_PostValues;
}
设置{
_PostValues=值;
}
}
///
///获取或设置要对url执行的操作的类型。
///
公共PostTypeEnum类型{
得到{
返回_PostType;
}
设置{
_PostType=值;
}
}
#端区
///
///将提供的数据发布到指定的url。
///
///包含post结果的字符串。
公共异步任务Post(){
StringBuilder参数=新的StringBuilder();
对于(int i=0;i<\u PostValues.Count;i++){
EncodeAndAddItem(ref参数,_PostValues.GetKey(i),_PostValues[i]);
}
字符串结果=等待PostData(_URL,parameters.ToString());
返回结果;
}
///
///将提供的数据发布到指定的url。
///
///要发布到的url。
///包含post结果的字符串。
公共异步任务发布(字符串url){
_URL=URL;
返回等待此。Post();
}
///
///将提供的数据发布到指定的url。
///
///要发布到的url。
///要发布的值。
///包含post结果的字符串。
公共异步任务Post(字符串url、NameValueCollection值){
_PostValues=值;
返回等待此。发布(url);
}
///
///将数据发布到指定的url。请注意,这假定您已经对发布数据进行了url编码。
///
///要发布的数据。
///要发布到的url。
///返回post的结果。
专用异步任务PostData(字符串url、字符串PostData){
HttpWebRequest请求=null;
if(_PostType==PostTypeEnum.POST){
Uri=新的Uri(url);
request=WebRequest.Create(uri)为HttpWebRequest;
request.Method=“POST”;
request.ContentType=“application/x-www-form-urlencoded”;
request.ContentLength=postData.Length;
使用(Stream writeStream=wait request.GetRequestStreamAsync()){
UTF8Encoding=新的UTF8Encoding();
字节[]字节=编码.GetBytes(postData);
writeStream.Write(字节,0,字节.长度);
}
}
否则{
Uri=新Uri(url+“?”+postData);
request=WebRequest.Create(uri)为HttpWebRequest;
request.Method=“GET”;
}
使用(HttpWebResponse=(HttpWebResponse)wait request.GetResponseAsync()){
使用(Stream responseStream=response.GetResponseStream()){
使用(streamreadstream=newstreamreader(responseStream,Encoding.UTF8)){
返回wait wait readStream.ReadToEndAsync();
}
}
}
}
///
///对项目进行编码并将其广告到字符串中。
///
///先前编码的数据。
///要编码的数据。
///包含旧数据和以前编码的数据的字符串。
私有void EncodeAndAddItem(参考StringBuilder baseRequest、字符串键、字符串数据项){
if(baseRequest==null){
巴塞雷克