2014-01-16 63 views
0

我使用多部分數據表單上傳文件,並且需要保留上傳文件的文件描述。我使用下面的代碼如何從異步任務中返回一些值

FileDescription temp = new FileDescription(); 
var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith<IEnumerable<FileDescription>>(t => 
{ 

    if (t.IsFaulted || t.IsCanceled) 
    { 
     throw new HttpResponseException(HttpStatusCode.InternalServerError); 
    } 

    var fileInfo = streamProvider.FileData.Select(i => 
    { 
     var info = new FileInfo(i.LocalFileName); 
     temp.AssociatedSchool = 1; 
     temp.FileName = info.Name; 
     temp.LocalFileName = i.LocalFileName; 
     temp.FileSize = info.Length/1024; 
     temp.IsFileValid = true; 
     temp.NoOfRecords = 1; 
     temp.UploadedBy = 1; 
     return temp; 
    }); 
    return fileInfo; 
}); 

此代碼犯規設定值的temp對象。任何人都可以告訴我一種替代方法來獲取值嗎? task.Result始終爲空。我如何從線程中獲取值?

+0

'Select'是懶惰的LINQ功能 – Grundy

+1

你開始或等待任務在哪裏? –

+0

@Grundy,是否有替代選擇? – NewBie

回答

1

試着改變你的樣品是這樣

var descriptions = Request.Content.ReadAsMultipartAsync(streamProvider) 
          .ContinueWith<IEnumerable<FileDescription>>(t => 
      { 
       if (t.IsFaulted || t.IsCanceled) 
       { 
        throw new HttpResponseException(HttpStatusCode.InternalServerError); 
       } 

       var fileInfo = streamProvider.FileData.Select(i => 
       { 
        var info = new FileInfo(i.LocalFileName); 
        return new FileDescription(){ 
         AssociatedSchool = 1; 
         FileName = info.Name; 
         LocalFileName = i.LocalFileName; 
         FileSize = info.Length/1024; 
         IsFileValid = true; 
         NoOfRecords = 1; 
         UploadedBy = 1; 
        } 
       }); 
       return fileInfo; 
      }).Result; 

var temp = descriptions.First();//Possibly you need FirstOrDefault