【发布时间】:2012-07-15 00:12:55
【问题描述】:
在下面的代码中,我试图在另一个线程中执行一个返回值的方法。但是,它只是不起作用!!!
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”。
【问题讨论】:
-
有人能告诉我错误的原因吗?还有一个关于斯蒂芬回答的讨论,我不明白同步/异步的逻辑。当我按照斯蒂芬的建议更改我的代码时,我收到另一个错误,另外,用户界面停止响应并且进度条的活动不可见。
标签: c# multithreading async-await