我对async/await编程很新,有时我觉得我理解它,然后突然发生了一些事情,并引发了我的循环.
我在测试winforms应用程序中尝试这个,这是我的一个版本的片段.这样做会阻止UI
private async void button1_Click(object sender, EventArgs e)
{
int d = await DoStuffAsync(c);
Console.WriteLine(d);
}
private async Task<int> DoStuffAsync(CancellationTokenSource c)
{
int ret = 0;
// I wanted to simulator a long running process this way
// instead of doing Task.Delay
for (int i = 0; i < 500000000; i++)
{
ret += i;
if (i % 100000 == 0)
Console.WriteLine(i);
if (c.IsCancellationRequested)
{
return ret;
}
}
return ret;
}
Run Code Online (Sandbox Code Playgroud)
现在,当我通过在Task.Run中包装"DoStuffAsync()"的主体进行轻微更改时,它的工作完全正常
private async Task<int> DoStuffAsync(CancellationTokenSource c)
{ …Run Code Online (Sandbox Code Playgroud) 使用web api时,如果使用,如何调用正确的路由方法 [RoutePrefix()]
假设您有类似"MyReallyLongNamedClassController"的内容.默认路由为http:... com/api/MyReallyLongNamedClass.然后应用程序通过名为Get,Post,Put等的方法(除非当然使用动词装饰器).
如果我[RoutePrefix("api/LongClass")]在我的控制器上放置一个路由前缀装饰器,我怎么能让web api仍然使用这些方法的默认值?
意思是,我希望名为"GetAll()"的方法仍然映射到"api/LongClass"(当使用get头时)和"PostThis(int id)"仍然映射到"api/LongClass/{id}"(当使用帖子标题时)