从 windows 服务调用时,Web 服务中的线程不会启动
Thread in a web service doesn't start when called it from windows service
我有一个 windows 服务,该服务主体中的代码采用经过计时器方法。
我在一个循环中调用一些 Web 服务,而那些 Web 服务 运行 在一个线程中。
我检查了服务器上的服务,它们没有启动。
当我从线程主体中取出代码时,那些代码起作用了。
这是我的 windows 从服务器调用网络服务的服务代码。
private void CallServiceForTrancoding(object sender, System.Timers.ElapsedEventArgs e)
{
DataSet.TranscodingVideosDataTable oTranscodingVideosDataTable = new DataSet.TranscodingVideosDataTable();
DataSetTableAdapters.TranscodingVideoTableAdapter oTranscodingVideoTableAdapter = new DataSetTableAdapters.TranscodingVideoTableAdapter();
oTranscodingVideoTableAdapter.FillVideosForTranscoding(oTranscodingVideosDataTable);
DataSet.ServersDataTable oServersDataTable = new DataSet.ServersDataTable();
DataSetTableAdapters.ServersTableAdapter oServersTableAdapter = new DataSetTableAdapters.ServersTableAdapter();
oServersTableAdapter.FillBaseOnConvertAction(oServersDataTable);
for (int i = 0; i < oTranscodingVideosDataTable.Count; i++)
{
if (oTranscodingVideosDataTable[i].IsQualityNull() == false)
{
var Qualities = oTranscodingVideosDataTable[i].Quality.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
string path = oTranscodingVideosDataTable[i].Path + oTranscodingVideosDataTable[i].ObjectUniqueName;
string[] Url = new string[Qualities.Length];
for (int j = 0; j < Qualities.Length; j++)
{
if (j == 0)
{
Url[j] = path;
}
else
{
Url[j] = path.Replace(path.Split('/').Last(), "") + path.Split('/').Last().Split('.')[0] + "-" + Qualities[j] + "." + path.Split('/').Last().Split('.')[1];
}
}
string parameters = "Token=" + "@HelloWorld" +
"&Url=" + new JavaScriptSerializer().Serialize(Url) +
"&FileUniqueName=" + oTranscodingVideosDataTable[i].ObjectUniqueName +
"&ip=" + oTranscodingVideosDataTable[i].IPValid +
"&GregoreanDate=" + oTranscodingVideosDataTable[i].Gorean_Date.ToString();
DataSet.VideoDataTable oVideoDataTable = new DataSet.VideoDataTable();
DataSetTableAdapters.VideoTableAdapter oVideoTableAdapter = new DataSetTableAdapters.VideoTableAdapter();
oVideoTableAdapter.UpdateVideoStatus(oTranscodingVideosDataTable[i].ObjectUniqueName);
string WebServiceOfServer = oServersDataTable[i].WebService;
WebServiceOfServer = WebServiceOfServer.Replace(WebServiceOfServer.Split('/').Last(), "RS");
JavaScriptSerializer objSerializer = new JavaScriptSerializer();
//Task a = Task.Factory.StartNew(() => {
Task ResponseResult = GetPostMethods.POST(WebServiceOfServer, parameters);
string JSONResult = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(ResponseResult);
var ResponseString = objSerializer.Deserialize<dynamic>(JSONResult);
var UserToken = ResponseString["Result"]["UserToken"];
var Successfully = ResponseString["Result"]["Successfully"];
//});
}
}
}
这是我的网络方法:
[WebMethod]
public void RS(string Token, string Url, string FileUniqueName, string ip,string GregoreanDate)
{
new Thread(() =>
{
if (Token != "HelloWorld")
{
}
else
{
try
{
var VideoUrl = new JavaScriptSerializer().Deserialize<string[]>(Url);
string[] FileName = new string[VideoUrl.Length];
string[] FilePath = new string[VideoUrl.Length];
t.VideoUniqueName = FileUniqueName.Split('.')[0];
t.mediaOutPath = HttpContext.Current.Server.MapPath("/video/") + DateTime.Parse(GregoreanDate).Year + "\" + DateTime.Parse(GregoreanDate).Month + "\" + FileUniqueName.Split('.')[0] + "\";
t.mediaOutFolderPath = "/video/" + DateTime.Parse(GregoreanDate).Year + "/" + DateTime.Parse(GregoreanDate).Month + "/";
if (!Directory.Exists(t.mediaOutPath))
{
Directory.CreateDirectory(t.mediaOutPath);
Directory.CreateDirectory(t.mediaOutPath + "m3u8\");
}
t.CreateFTPPathForVideoScheduler(t.VideoTypeFormKey, t.mediaOutPath);
string Paths = "";
for (int i = 0; i < VideoUrl.Length; i++)
{
FileName[i] = VideoUrl[i].Split('/').Last();
if (FileName[i] != FileUniqueName)
{
FilePath[i] = t.mediaOutPath + FileName[i];
}
else
{
FilePath[i] = t.ffmpegFolderPath + FileName[i];
}
using (WebClient client = new WebClientWithAwesomeTimeouts { Timeout = new TimeSpan(10, 0, 0, 0) })
{
try
{
client.DownloadFile(VideoUrl[i], FilePath[i]);
client.Dispose();
}
catch (Exception ex)
{
StreamWriter sw = new StreamWriter(t.LogPath, true);
sw.WriteLine(ex.Message + "----" + ex.StackTrace != null ? ex.StackTrace : "" + "----" + DateTime.Now);
sw.Close();
}
}
}
DirectoryInfo FilesDirectory = new DirectoryInfo(t.ffmpegFolderPath);
FileInfo[] fInfo = FilesDirectory.GetFiles("*" + FileUniqueName.Split('.')[0] + "*.*");
fInfo[0].CopyTo(t.mediaOutPath + FileUniqueName, true);
t.SendFileWithFTPScheduler(t.VideoTypeFormKey, t.mediaOutPath + FileUniqueName);
FilesDirectory = new DirectoryInfo(t.mediaOutPath);
fInfo = FilesDirectory.GetFiles("*" + FileUniqueName.Split('.')[0] + "*.*");
foreach (FileInfo file in fInfo)
{
t.SendFileWithFTPScheduler(t.VideoTypeFormKey, file.FullName);
}
string UniqueFilePath = FilePath[0].Replace(FilePath[0].Split('/').Last(), FileUniqueName);
JavaScriptSerializer objSerializer = new JavaScriptSerializer();
var VideoDimensions = objSerializer.Deserialize<Dictionary<string, string>>(t.getVideoHeightAndWidth(t.ffmpegFolderPath + UniqueFilePath));
string Width = VideoDimensions["Width"];
string Height = VideoDimensions["Height"];
Transcoding.VideoResolutions vr = new Transcoding.VideoResolutions();
var VideoResolutionsInfo = objSerializer.Deserialize<Dictionary<object, object>>(t.getVideoResolution(Height));
vr.OrginalResolution = VideoResolutionsInfo["OrginalResolution"].ToString();
vr.ResCount = Convert.ToInt32(VideoResolutionsInfo["ResCount"]);
vr.OrginalResIndex = Convert.ToInt32(VideoResolutionsInfo["OrginalResIndex"]);
vr.UpperResolutionHeight = VideoResolutionsInfo["UpperResolutionHeight"].ToString();
t.MakeM3U8FormatScheduler(FileUniqueName, vr.OrginalResolution, vr.ResCount, vr.OrginalResIndex, false, "", Height);
t.ProcessFilesScheduler(t.mediaOutPath + "m3u8\", t.VideoTypeFormKey);
DataSet.VideoDataTable oVideoDataTable = new DataSet.VideoDataTable();
DataSetTableAdapters.VideoTableAdapter oVideoTableAdapter = new DataSetTableAdapters.VideoTableAdapter();
oVideoTableAdapter.UpdateVideoForAcceptation(1, true, "mp4,m3u8", "http://" + t.mediaOutFolderPath + t.VideoUniqueName + "/", FileUniqueName);
oVideoTableAdapter.UpdateStatus("resfinish", FileUniqueName);
foreach (string path in VideoUrl)
{
if (path.ToLower().Contains("mp4videos"))
{
t.FTPDelete(new Uri(path.Replace(new Uri(path).Host, ip).Replace("http", "ftp")));
}
}
System.IO.File.Delete(t.ffmpegFolderPath + UniqueFilePath);
System.IO.Directory.Delete(t.mediaOutPath, true);
}
catch (Exception ex)
{
}
}
}).Start();
}
Task ResponseResult = GetPostMethods.POST(WebServiceOfServer, parameters);
string JSONResult = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(ResponseResult);
您正在序列化任务。你肯定很想等结果吧?
我调试了我的网络服务,发现问题与 httpcontext.current
in thread is null 有关。
为此,我将 HttpContext.Current.Server.MapPath("/video/")
定义为 class 中的一个变量,并从网络服务中调用它。
我有一个 windows 服务,该服务主体中的代码采用经过计时器方法。
我在一个循环中调用一些 Web 服务,而那些 Web 服务 运行 在一个线程中。
我检查了服务器上的服务,它们没有启动。
当我从线程主体中取出代码时,那些代码起作用了。
这是我的 windows 从服务器调用网络服务的服务代码。
private void CallServiceForTrancoding(object sender, System.Timers.ElapsedEventArgs e)
{
DataSet.TranscodingVideosDataTable oTranscodingVideosDataTable = new DataSet.TranscodingVideosDataTable();
DataSetTableAdapters.TranscodingVideoTableAdapter oTranscodingVideoTableAdapter = new DataSetTableAdapters.TranscodingVideoTableAdapter();
oTranscodingVideoTableAdapter.FillVideosForTranscoding(oTranscodingVideosDataTable);
DataSet.ServersDataTable oServersDataTable = new DataSet.ServersDataTable();
DataSetTableAdapters.ServersTableAdapter oServersTableAdapter = new DataSetTableAdapters.ServersTableAdapter();
oServersTableAdapter.FillBaseOnConvertAction(oServersDataTable);
for (int i = 0; i < oTranscodingVideosDataTable.Count; i++)
{
if (oTranscodingVideosDataTable[i].IsQualityNull() == false)
{
var Qualities = oTranscodingVideosDataTable[i].Quality.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
string path = oTranscodingVideosDataTable[i].Path + oTranscodingVideosDataTable[i].ObjectUniqueName;
string[] Url = new string[Qualities.Length];
for (int j = 0; j < Qualities.Length; j++)
{
if (j == 0)
{
Url[j] = path;
}
else
{
Url[j] = path.Replace(path.Split('/').Last(), "") + path.Split('/').Last().Split('.')[0] + "-" + Qualities[j] + "." + path.Split('/').Last().Split('.')[1];
}
}
string parameters = "Token=" + "@HelloWorld" +
"&Url=" + new JavaScriptSerializer().Serialize(Url) +
"&FileUniqueName=" + oTranscodingVideosDataTable[i].ObjectUniqueName +
"&ip=" + oTranscodingVideosDataTable[i].IPValid +
"&GregoreanDate=" + oTranscodingVideosDataTable[i].Gorean_Date.ToString();
DataSet.VideoDataTable oVideoDataTable = new DataSet.VideoDataTable();
DataSetTableAdapters.VideoTableAdapter oVideoTableAdapter = new DataSetTableAdapters.VideoTableAdapter();
oVideoTableAdapter.UpdateVideoStatus(oTranscodingVideosDataTable[i].ObjectUniqueName);
string WebServiceOfServer = oServersDataTable[i].WebService;
WebServiceOfServer = WebServiceOfServer.Replace(WebServiceOfServer.Split('/').Last(), "RS");
JavaScriptSerializer objSerializer = new JavaScriptSerializer();
//Task a = Task.Factory.StartNew(() => {
Task ResponseResult = GetPostMethods.POST(WebServiceOfServer, parameters);
string JSONResult = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(ResponseResult);
var ResponseString = objSerializer.Deserialize<dynamic>(JSONResult);
var UserToken = ResponseString["Result"]["UserToken"];
var Successfully = ResponseString["Result"]["Successfully"];
//});
}
}
}
这是我的网络方法:
[WebMethod]
public void RS(string Token, string Url, string FileUniqueName, string ip,string GregoreanDate)
{
new Thread(() =>
{
if (Token != "HelloWorld")
{
}
else
{
try
{
var VideoUrl = new JavaScriptSerializer().Deserialize<string[]>(Url);
string[] FileName = new string[VideoUrl.Length];
string[] FilePath = new string[VideoUrl.Length];
t.VideoUniqueName = FileUniqueName.Split('.')[0];
t.mediaOutPath = HttpContext.Current.Server.MapPath("/video/") + DateTime.Parse(GregoreanDate).Year + "\" + DateTime.Parse(GregoreanDate).Month + "\" + FileUniqueName.Split('.')[0] + "\";
t.mediaOutFolderPath = "/video/" + DateTime.Parse(GregoreanDate).Year + "/" + DateTime.Parse(GregoreanDate).Month + "/";
if (!Directory.Exists(t.mediaOutPath))
{
Directory.CreateDirectory(t.mediaOutPath);
Directory.CreateDirectory(t.mediaOutPath + "m3u8\");
}
t.CreateFTPPathForVideoScheduler(t.VideoTypeFormKey, t.mediaOutPath);
string Paths = "";
for (int i = 0; i < VideoUrl.Length; i++)
{
FileName[i] = VideoUrl[i].Split('/').Last();
if (FileName[i] != FileUniqueName)
{
FilePath[i] = t.mediaOutPath + FileName[i];
}
else
{
FilePath[i] = t.ffmpegFolderPath + FileName[i];
}
using (WebClient client = new WebClientWithAwesomeTimeouts { Timeout = new TimeSpan(10, 0, 0, 0) })
{
try
{
client.DownloadFile(VideoUrl[i], FilePath[i]);
client.Dispose();
}
catch (Exception ex)
{
StreamWriter sw = new StreamWriter(t.LogPath, true);
sw.WriteLine(ex.Message + "----" + ex.StackTrace != null ? ex.StackTrace : "" + "----" + DateTime.Now);
sw.Close();
}
}
}
DirectoryInfo FilesDirectory = new DirectoryInfo(t.ffmpegFolderPath);
FileInfo[] fInfo = FilesDirectory.GetFiles("*" + FileUniqueName.Split('.')[0] + "*.*");
fInfo[0].CopyTo(t.mediaOutPath + FileUniqueName, true);
t.SendFileWithFTPScheduler(t.VideoTypeFormKey, t.mediaOutPath + FileUniqueName);
FilesDirectory = new DirectoryInfo(t.mediaOutPath);
fInfo = FilesDirectory.GetFiles("*" + FileUniqueName.Split('.')[0] + "*.*");
foreach (FileInfo file in fInfo)
{
t.SendFileWithFTPScheduler(t.VideoTypeFormKey, file.FullName);
}
string UniqueFilePath = FilePath[0].Replace(FilePath[0].Split('/').Last(), FileUniqueName);
JavaScriptSerializer objSerializer = new JavaScriptSerializer();
var VideoDimensions = objSerializer.Deserialize<Dictionary<string, string>>(t.getVideoHeightAndWidth(t.ffmpegFolderPath + UniqueFilePath));
string Width = VideoDimensions["Width"];
string Height = VideoDimensions["Height"];
Transcoding.VideoResolutions vr = new Transcoding.VideoResolutions();
var VideoResolutionsInfo = objSerializer.Deserialize<Dictionary<object, object>>(t.getVideoResolution(Height));
vr.OrginalResolution = VideoResolutionsInfo["OrginalResolution"].ToString();
vr.ResCount = Convert.ToInt32(VideoResolutionsInfo["ResCount"]);
vr.OrginalResIndex = Convert.ToInt32(VideoResolutionsInfo["OrginalResIndex"]);
vr.UpperResolutionHeight = VideoResolutionsInfo["UpperResolutionHeight"].ToString();
t.MakeM3U8FormatScheduler(FileUniqueName, vr.OrginalResolution, vr.ResCount, vr.OrginalResIndex, false, "", Height);
t.ProcessFilesScheduler(t.mediaOutPath + "m3u8\", t.VideoTypeFormKey);
DataSet.VideoDataTable oVideoDataTable = new DataSet.VideoDataTable();
DataSetTableAdapters.VideoTableAdapter oVideoTableAdapter = new DataSetTableAdapters.VideoTableAdapter();
oVideoTableAdapter.UpdateVideoForAcceptation(1, true, "mp4,m3u8", "http://" + t.mediaOutFolderPath + t.VideoUniqueName + "/", FileUniqueName);
oVideoTableAdapter.UpdateStatus("resfinish", FileUniqueName);
foreach (string path in VideoUrl)
{
if (path.ToLower().Contains("mp4videos"))
{
t.FTPDelete(new Uri(path.Replace(new Uri(path).Host, ip).Replace("http", "ftp")));
}
}
System.IO.File.Delete(t.ffmpegFolderPath + UniqueFilePath);
System.IO.Directory.Delete(t.mediaOutPath, true);
}
catch (Exception ex)
{
}
}
}).Start();
}
Task ResponseResult = GetPostMethods.POST(WebServiceOfServer, parameters);
string JSONResult = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(ResponseResult);
您正在序列化任务。你肯定很想等结果吧?
我调试了我的网络服务,发现问题与 httpcontext.current
in thread is null 有关。
为此,我将 HttpContext.Current.Server.MapPath("/video/")
定义为 class 中的一个变量,并从网络服务中调用它。