我正在为一个网站编写视频转换工具。使用c#等待后,部分代码无法访问
Logic是下一个
- 用户上传的文件
- 系统CONVER它为用户(而转换当然用户不应等待)
我有一个代码:
public async void AddVideo(HotelVideosViewModel model)
{
var sourceFile = FileHandler.SaveFile(model.VideoFile);
var fullFilePath = HttpContext.Current.Server.MapPath(sourceFile);
await Task.Factory.StartNew(() => video.Convert(fullFilePath));
model.FileLocation = sourceFile;
model.IsConverted = true;
this.Add<HotelVideos>(Mapper.Map<HotelVideosViewModel, HotelVideos>(model));
}
此开始编码:
await Task.Factory.StartNew(() => video.Convert(fullFilePath));
但是之后的代码永远不会执行......有人有解决方案吗?
PS:下video.Conver(...)是有这样的事:
public bool Convert(string fileLocation)
{
// do staff
}
--- UPDATE ---
刚拿到有趣的事情。如果我要将video.Convert(fullFilePath)
换成Thread.Sleep(2000),一切都开始奏效。所以问题在于我想第二种方法。
所以我添加下一个文件的代码(草案至今):
using Softpae.Media;
/// <summary>
/// TODO: Update summary.
/// </summary>
public class VideoConvertManager
{
private readonly Job2Convert jobConverter = new Job2Convert();
private readonly MediaServer mediaServer = new MediaServer();
public bool Convert(string fileLocation)
{
this.jobConverter.pszSrcFile = fileLocation;
this.jobConverter.pszDstFile = fileLocation + ".mp4";
this.jobConverter.pszDstFormat = "mp4";
this.jobConverter.pszAudioCodec = null;
this.jobConverter.pszVideoCodec = "h264";
if (this.mediaServer.ConvertFile(this.jobConverter))
{
FileHandler.DeleteFile(fileLocation);
return true;
};
FileHandler.DeleteFile(fileLocation);
return false;
}
}
PPS。这是我第一次使用异步/等待:) – 2012-07-31 20:56:14
等待不会返回,直到转换完成,是否转换完成? – Frobzig 2012-07-31 21:10:40
你有没有试过这个教程? http://msdn.microsoft.com/en-us/library/hh300224(v=vs.110).aspx – cshemby 2012-07-31 21:13:51