想知道是否可以通过await调用返回字符串。
public static async Task<string[]> GetCode(IEnumerable<CodeAddressContainer> codeList, int count)
{
string[] stringArray = new string[count];
await Task.Run(() => Parallel.ForEach(codeList, code =>
{
var id = code.Id;
var asm = code.ASM;
var address = code.Address;
var hexCode = CompileCodeToPairedHex(asm);
var lines = hexCode.GetNonEmptyLineCount();
address = GetInsertionAddress(address, lines);
string result = address + Environment.NewLine + hexCode;
stringArray[id] = result;
}));
return stringArray;
}
如果可能的话,会更顺畅一点。
我无法找到关于你可以通过它返回的价值的任何信息。
只有我有异步任务的原因只是为了能够运行方法异步。
答案 0 :(得分:1)
这个怎么样:
public static async Task<string[]> GetCode(IEnumerable<CodeAddressContainer> codeList, int count)
{
return await Task.Run<string[]>(() => codeList.AsParallel().AsOrdered().Select(code =>
{
var id = code.Id;
var asm = code.ASM;
var address = code.Address;
var hexCode = CompileCodeToPairedHex(asm);
var lines = hexCode.GetNonEmptyLineCount();
address = GetInsertionAddress(address, lines);
string result = address + Environment.NewLine + hexCode;
return result;
}).ToArray());
}
答案 1 :(得分:0)
不,你不能从Task.Run
返回,因为它是一个等待的内部函数,这意味着此时控件将被发送回调用者。
但是,如果您只关心保留方法async
,您可以在使用等待将IENumerable
转换为列表的行中执行某些操作,其余的很容易:
public static async Task<string[]> GetCode(IEnumerable<CodeAddressContainer> codeList, int count)
{
var list = await codeList.ToListAsync();
string[] stringArray = new string[count];
Parallel.ForEach(codeList, code =>
{
var id = code.Id;
var asm = code.ASM;
var address = code.Address;
var hexCode = CompileCodeToPairedHex(asm);
var lines = hexCode.GetNonEmptyLineCount();
address = GetInsertionAddress(address, lines);
string result = address + Environment.NewLine + hexCode;
stringArray[id] = result;
}
return stringArray;
}