[英]How to release thread from deadlock in async & await
I am using async & await method for download the project VSO API, but some time thread never returns and it continuously await the stream data. 我正在使用async&await方法下载项目VSO API,但是有些时间线程永远不会返回,并且它会持续等待流数据。 So what should I need to do in case.
所以我该怎么办以防万一。 I don't know the approx time for download.
我不知道大概的下载时间。 If we can do anything that thread who is waiting more than 24 hour get suspend.
如果我们可以做任何事情,等待24小时以上的线程将被暂停。
Please suggest in below lines code- 请在下面的代码行中建议-
public static async Task<string> DownloadProject(string Project, string sourceUrl, string targetdir, string BackPlanName, int callbyservice)
{
FileStream fileStream = null;
DateTime starttime = DateTime.Now;
string str = "";
ILogger ilogger = new Logger();
ConfigurationSettings objXConfiguration = new ConfigurationSettings();
System.Net.ServicePointManager.Expect100Continue = false;
try
{
var username = objConfigurationSettings.UserName;
var password = objConfigurationSettings.Password;
using (HttpClient client = new HttpClient())
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/zip"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", username, password))));
client.DefaultRequestHeaders.Add("Connection", new string[] { "Keep-Alive" });
//=============================================================================================================
string FilePath = targetdir + "\\" + BackPlanName;
// string CurrentDate = DateTime.Now.Day.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Year.ToString() + "-" + DateTime.Now.Hour.ToString() + "-" + DateTime.Now.Minute.ToString() + "-" + DateTime.Now.Second;
str = Project + ".zip";
if (!Directory.Exists(FilePath))
{
Directory.CreateDirectory(FilePath);
}
fileStream = new FileStream(FilePath + "\\" + str, FileMode.Create, FileAccess.Write);
System.Net.ServicePointManager.Expect100Continue = false;
var stream = await client.GetStreamAsync(sourceUrl).ConfigureAwait(continueOnCapturedContext: false);
await stream.CopyToAsync(fileStream).ConfigureAwait(continueOnCapturedContext: false);
//===========================================================================
return FilePath + "\\" + str;
}
}
catch (Exception e)
{
throw e;
}
finally {
}
}
JUST USE OF Cancellation Token 只需使用取消令牌
public static async Task DownloadProject(string Project, string sourceUrl, string targetdir, string BackPlanName, int callbyservice) { CancellationTokenSource cts = new CancellationTokenSource(); 公共静态异步任务DownloadProject(字符串项目,字符串sourceUrl,字符串targetdir,字符串BackPlanName,int callbyservice){CancellationTokenSource cts = new CancellationTokenSource(); cts.CancelAfter(1000*60*60*23);
cts.CancelAfter(1000 * 60 * 60 * 23); FileStream fileStream = null;
FileStream fileStream = null; DateTime starttime = DateTime.Now;
DateTime开始时间= DateTime.Now; string str = "";
字符串str =“”; ILogger ilogger = new Logger();
ILogger ilogger =新的Logger(); ConfigurationSettings objXConfiguration = new ConfigurationSettings();
ConfigurationSettings objXConfiguration =新的ConfigurationSettings(); System.Net.ServicePointManager.Expect100Continue = false;
System.Net.ServicePointManager.Expect100Continue =否; try { var username = objConfigurationSettings.UserName;
尝试{var username = objConfigurationSettings.UserName; var password = objConfigurationSettings.Password;
var password = objConfigurationSettings.Password; using (HttpClient client = new HttpClient()) {
使用(HttpClient client = new HttpClient()){
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/zip"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", username, password))));
client.DefaultRequestHeaders.Add("Connection", new string[] { "Keep-Alive" });
//=============================================================================================================
string FilePath = targetdir + "\\" + BackPlanName;
// string CurrentDate = DateTime.Now.Day.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Year.ToString() + "-" + DateTime.Now.Hour.ToString() + "-" + DateTime.Now.Minute.ToString() + "-" + DateTime.Now.Second;
str = Project + ".zip";
if (!Directory.Exists(FilePath))
{
Directory.CreateDirectory(FilePath);
}
fileStream = new FileStream(FilePath + "\\" + str, FileMode.Create, FileAccess.Write);
System.Net.ServicePointManager.Expect100Continue = false;
var stream = await client.GetStreamAsync(sourceUrl).ConfigureAwait(continueOnCapturedContext: false);
await stream.CopyToAsync(fileStream,81920,cts.Token).ConfigureAwait(continueOnCapturedContext: true);
string CalculateSize = CalculateFileSize(FilePath + "\\" + str);
object _lock = new object();
IXMLData ixmlBackup = new XMLData();
EventWaitHandle waitHandle = new EventWaitHandle(true, EventResetMode.AutoReset);
waitHandle.WaitOne();
ixmlBackup.CreateBackupResultXML(UtlityHelper.GetFilePath(Settings.Default.BackupResult), BackPlanName, starttime.ToString(), DateTime.Now.ToString(), "Success", CalculateSize + " files copied");
waitHandle.Set();
// waitHandle.Dispose();
//==================Email when download compelte in window service===========================//
if (callbyservice == 1)
{
objXConfiguration = ixmlBackup.GetSettings("application");
ObservableCollection<BackupPlan> BackupPlanCollection = ixmlBackup.GetBackupPlan();
var CurrentPlan = BackupPlanCollection.Where(r => r.BackupPlanName == BackPlanName).FirstOrDefault();
DeleteFile(CurrentPlan.KeepBackupFileCount, CurrentPlan.TargetLocation + CurrentPlan.BackupPlanName, objXConfiguration.EmailAlertLevel, objConfigurationSettings.Service, ilogger);
if (objXConfiguration.EmailAlertLevel == "1" || objXConfiguration.EmailAlertLevel == "2")
{
UtlityHelper.SendEmail(DateTime.Now.ToString() + ":" + objConfigurationSettings.Service + ":The download for the backup profile "+BackPlanName+" completed.", 1);
}
ilogger.WriteBackLog(DateTime.Now.ToString() + ":" + objConfigurationSettings.Service + ":The download for the backup profile " + BackPlanName + " completed.");
}
//===========================================================================
return FilePath + "\\" + str;
}
}
catch (Exception e)
{
IXMLData ixmlBackup = new XMLData();
ixmlBackup.CreateBackupResultXML(UtlityHelper.GetFilePath(Settings.Default.BackupResult), BackPlanName, starttime.ToString(), DateTime.Now.ToString(), "Fail", e.Message);
if (callbyservice == 1)
{
ilogger.WriteBackupException(e);
objXConfiguration = ixmlBackup.GetSettings("application");
if (objXConfiguration.EmailAlertLevel == "0" || objXConfiguration.EmailAlertLevel == "2")
{
UtlityHelper.SendEmail(DateTime.Now.ToString() + ":" + objConfigurationSettings.Service + ": Exception:" + BackPlanName + ":" + e.Message, 1);
}
}
else
{
throw e;
}
return null;
}
finally {
fileStream.Flush();
fileStream.Dispose();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.