在下面的代碼,我試圖執行一個方法,它返回一個值,在另一個線程。但是,它只是不工作!多線程帶有Async給出了類型轉換誤差()
public void main()
{
lstChapters.DataContext = await TaskEx.WhenAll(LoadChapters());
}
//CAN'T use async in this function, it requires Task<> which
//Error appears on the code inside []
public [async Task<object>] Convert(object[] values, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
dictChapters data = await IQ_LoadQuranXML.LoadChapters(TypeIndex);
}
internal static async Task< IEnumerable<dictChapters>> LoadChapters()
{
var element = XElement.Load("xml/chapters.xml");
Task < IEnumerable <dictChapters>> something = (Task<IEnumerable<dictChapters>>) await TaskEx.Run(delegate
{
IEnumerable<dictChapters> Chapters =
from var in element.Descendants("chapter")
orderby var.Attribute("index").Value
select new dictChapters
{
ChapterIndex = Convert.ToInt32(var.Attribute("index").Value),
ChapterArabicName = var.Attribute("name").Value,
ChapterType = var.Attribute("type").Value,
};
return Chapters;}
);
return something; //An ERROR on this line
}
//Overriding method which does not return IEnumerable type. And it accepts index as integer.
internal static dictChapters LoadChapters(string chIdx = "0")
{
int chIdxInt = Convert.ToInt32(chIdx);
List<dictChapters> Chapters = (List<dictChapters>) LoadChapters(); // ERROR is on this line too
return Chapters.ElementAt(chIdxInt - 1); //index of chapter in the element starts from 0
}
的錯誤是:
無法隱式轉換類型 '
System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<iq_main.dictChapters>>
' 到 'System.Collections.Generic.IEnumerable<iq_main.dictChapters>
'。一個顯式轉換存在(是否缺少強制轉換?)
,另一個錯誤是..
無法將類型 '
System.Threading.Tasks.Task<System.Collections.Generic.List<iq_main.dictChapters>>
' 到'System.Collections.Generic.List<iq_main.dictChapters>
當我投「某事「明確地像return (IEnumerable<dictChapters>) something
然後在運行時,我得到」InvalidCastException「。
可能有人請告訴我的錯誤(或多個)的原因是什麼?也有是對答案的討論Stephen,我不明白Sync/Async的邏輯,當我按照Stephen的建議更改我的代碼時,出現另一個錯誤,此外,UI停止響應,進度條的活動不可見 – wafers 2012-07-15 10:55:17