从Windows服务

时间:2018-01-29 16:15:50

标签: c# multithreading windows-services elapsedtime

我有一个Windows服务,该主体中的代码是一个经过时间的计时器方法。
我在循环中调用一些Web服务,这些Web服务在一个线程中运行。 我检查了服务器上的服务,他们没有启动。
当我从线体中取出代码时,那些工作。
这是我的Windows服务代码,它从服务器调用webservices。

    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();
}

2 个答案:

答案 0 :(得分:0)

Task ResponseResult = GetPostMethods.POST(WebServiceOfServer, parameters);
string JSONResult = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(ResponseResult);

您正在序列化任务。你肯定想等待结果,不是吗?

答案 1 :(得分:0)

我调试了我的Web服务,发现问题与线程中的httpcontext.current有关。
为此,我将HttpContext.Current.Server.MapPath("/video/")定义为类中的变量,我从Web服务中调用它。