我有多个任务返回我想要调用的相同对象类型 Task.WhenAll(new[]{t1,t2,t3}); 并读取结果.
当我尝试使用时
Task<List<string>> all = await Task.WhenAll(new Task[] { t, t2 }).ConfigureAwait(false);
Run Code Online (Sandbox Code Playgroud)
我收到编译器错误
无法隐式转换类型'void'
'System.Threading.Tasks.Task<System.Collections.Generic.List<string>>
这两个任务都是类似的调用方法.
private Task<List<string>> GetFiles(string path)
{
files = new List<string>();
return Task.Run(() =>
{
//remove for brevity
return files;
});
}
Run Code Online (Sandbox Code Playgroud) 此函数根据其调用方式返回两个不同的值.我理解Closures关闭变量,而不是结束值,我期望从第二次调用返回的值是相同的,无论函数如何被调用
static Func<int, int,int> Sum()
{
var test = 1;
return (op1, op2) =>
{
test = test + 1;
return (op1 + op2) + test;
};
}
Run Code Online (Sandbox Code Playgroud)
这是电话:
var mFunc = Sum();
Console.WriteLine("Calling Sum(1,1) with Invoke() " + Sum().Invoke(1, 1));
Console.WriteLine("Calling Sum(2,2) with Invoke() " + Sum().Invoke(2, 2));
Console.WriteLine("Calling mFunc(1,1)" + mFunc(1, 1));
Console.WriteLine("Calling mFunc(2,2)" + mFunc(2, 2));
Console.Read();
Run Code Online (Sandbox Code Playgroud)
使用Invoke的结果:
4
6
Run Code Online (Sandbox Code Playgroud)
使用赋值变量的结果:
4
7
Run Code Online (Sandbox Code Playgroud)
为什么使用Invoke会更改闭包行为?
我正在读Lazy,我在Msdn docs上看到了这个警告说明
使Lazy对象线程安全不会保护延迟初始化对象.如果多个线程可以访问延迟初始化的对象,则必须使其属性和方法对多线程访问安全.
这是否意味着我们必须对所有属性应用线程安全措施?如果是,那么懒人服务的目的是什么?
谢谢
有人可以向我解释为什么这段代码不起作用(结果没有分配给文本框的文本属性)
private async Task<string> NumToString(int num)
{
return await new Task<string>(()=>{
return num.ToString();
});
}
Run Code Online (Sandbox Code Playgroud)
这是电话:
private async void button2_Click(object sender, EventArgs e)
{
// TaskScheduler context = TaskScheduler.FromCurrentSynchronizationContext();
var content = await NumToString(1);
textBox1.Text = content;
}
Run Code Online (Sandbox Code Playgroud)
此外,如果我取消注释TaskScheduler行,则会触发click事件,但NumTostring(1)不会触发.