如何中止一个正在执行中的方法(求助)C#

如何中止一个正在执行中的方法(求助)C#,第1张

主要做法有以下两种:

1. 多线程 *** 作,对线程进行定时,如果超时则停止。这个机制微软给出了BackgroundWorker,但是不够灵活不建议使用。优点是足够灵活,代码比较优雅。

private void DoQuery()

{

//Query work

}

private void start()

{

Thread th = new Thread(new ThreadStart(this.DoQuery))

th.Start()

DateTime dt1 = DateTime.Now

While(th.ThreadState != ThreadState.Stopped)

{

if((DateTime.Now-dt1).Seconds>5)

{

try

{

th.Abort()

}

catch

{

}

break

}

Application.DoEvent()

}

}

2. 使用数据库查询的超时,不过不是楼上说道的ConnectionTimeout而是Query的CommandTimeout,可以在SqlCommand中设置。建议使用这个(不过一定不要忘记捕捉异常)!

如果是SQL Server的话

SqlCommand comm = new comm(sql,con)

comm.CommandTimeout = 3

try

{

comm.ExecuteNonQuery():

}

catch

{

Console.WriteLine("TimeOut")

}

}

Ps:如果是linq的话,在DataContext中有CommandTimeout属性,设置这个就可以控制SubmitChanges的超时时间。其他的关于异常捕捉的做法和上面的一样。

这是因为该方法在未接收到目标机器的信息时会在这等着和accept方法一样,这里可以设置一个超时

socket.ReceiveTimeout = 5000 //设置超时时间

try

{

nBytes = socket.ReceiveFrom(ReceiveBuffer, 256, 0, ref EndPointFrom)

}

catch(Exception e) //捕捉超时这个事件

{

return "主机没有响应"

recd = true

}

出现这种情况,很可能是数据接收端和发送端网络没连接,或端口未开放(防火墙设置),再有可能是使用的网络层不同。

实例化下面的类,设置相关属性(url,method)等,调用call就好

using System

using System.Collections.Generic

using System.Linq

using System.Text

using System.Security.Cryptography.X509Certificates

using System.Net.Security

using System.IO

using System.Net

using System.Xml

namespace xxxu

{

public class XXXUHttpClient

{

//请求内容,无论post和get,都用get方式提供

private string reqContent

//应答内容

private string resContent

//请求方法

private string method

//错误信息

private string errInfo

//证书文件

private string certFile

//证书密码

private string certPasswd

//ca证书文件

private string caFile

//超时时间,以秒为单位

private int timeOut

//http应答编码

private int responseCode

//字符编码

private string charset

public HuizeHttpClient()

{

this.caFile = ""

this.certFile = ""

this.certPasswd = ""

this.reqContent = ""

this.resContent = ""

this.method = "POST"

this.errInfo = ""

this.timeOut = 1 * 60//5分钟

this.responseCode = 0

setCharset(System.Web.HttpContext.Current.Request.ContentEncoding.BodyName)

}

//设置请求内容

public void setReqContent(string reqContent)

{

this.reqContent = reqContent

}

//获取结果内容

public string getResContent()

{

return this.resContent

}

//设置请求方法post或者get

public void setMethod(string method)

{

this.method = method

}

//获取错误信息

public string getErrInfo()

{

return this.errInfo

}

//设置证书信息

public void setCertInfo(string certFile, string certPasswd)

{

this.certFile = certFile

this.certPasswd = certPasswd

}

//设置ca

public void setCaInfo(string caFile)

{

this.caFile = caFile

}

//设置超时时间,以秒为单位

public void setTimeOut(int timeOut)

{

this.timeOut = timeOut

}

//获取http状态码

public int getResponseCode()

{

return this.responseCode

}

public void setCharset(string charset)

{

if (string.IsNullOrEmpty(charset))

{

this.charset = "UTF-8"

}

this.charset = charset

}

//验证服务器证书

public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)

{

return true

}

//执行http调用

public bool call()

{

StreamReader sr = null

HttpWebResponse wr = null

HttpWebRequest hp = null

try

{

string postData = null

if (this.method.ToUpper() == "POST")

{

string[] sArray = System.Text.RegularExpressions.Regex.Split(this.reqContent, "\\?")

hp = (HttpWebRequest)WebRequest.Create(sArray[0])

if (sArray.Length >= 2)

{

postData = sArray[1]

}

}

else

{

hp = (HttpWebRequest)WebRequest.Create(this.reqContent)

}

ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult)

if (this.certFile != "")

{

hp.ClientCertificates.Add(new X509Certificate2(this.certFile, this.certPasswd))

}

hp.Timeout = this.timeOut * 1000

System.Text.Encoding encoding = System.Text.Encoding.GetEncoding(this.charset)

if (postData != null)

{

byte[] data = encoding.GetBytes(postData)

hp.Method = "POST"

hp.ContentType = "application/x-www-form-urlencoded"

hp.ContentLength = data.Length

Stream ws = hp.GetRequestStream()

// 发送数据

ws.Write(data, 0, data.Length)

ws.Close()

}

wr = (HttpWebResponse)hp.GetResponse()

sr = new StreamReader(wr.GetResponseStream(), encoding)

this.resContent = sr.ReadToEnd()

sr.Close()

wr.Close()

}

catch (Exception exp)

{

this.errInfo += exp.Message

if (wr != null)

{

this.responseCode = Convert.ToInt32(wr.StatusCode)

}

return false

}

this.responseCode = Convert.ToInt32(wr.StatusCode)

return true

}

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/11210625.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-14
下一篇 2023-05-14

发表评论

登录后才能评论

评论列表(0条)

保存