我刚看到3个关于TPL使用的例程,它们执行相同的工作; 这是代码:
public static void Main()
{
Thread.CurrentThread.Name = "Main";
// Create a task and supply a user delegate by using a lambda expression.
Task taskA = new Task( () => Console.WriteLine("Hello from taskA."));
// Start the task.
taskA.Start();
// Output a message from the calling thread.
Console.WriteLine("Hello from thread '{0}'.",
Thread.CurrentThread.Name);
taskA.Wait();
}
public static void Main()
{
Thread.CurrentThread.Name = "Main";
// Define and run the task.
Task taskA = Task.Run( () => Console.WriteLine("Hello from taskA."));
// Output a …
Run Code Online (Sandbox Code Playgroud) 所以我最近被告知我如何使用我的.ContinueWith for Tasks并不是使用它们的正确方法.我还没有在互联网上找到这方面的证据,所以我会问你们,看看答案是什么.这是我如何使用的例子.ContinueWith:
public Task DoSomething()
{
return Task.Factory.StartNew(() =>
{
Console.WriteLine("Step 1");
})
.ContinueWith((prevTask) =>
{
Console.WriteLine("Step 2");
})
.ContinueWith((prevTask) =>
{
Console.WriteLine("Step 3");
});
}
Run Code Online (Sandbox Code Playgroud)
现在我知道这是一个简单的例子,它运行得非常快,但只是假设每个任务都进行了更长时间的操作.所以,我被告知在.ContinueWith中,你需要说prevTask.Wait(); 否则你可以在上一个任务完成之前完成工作.这甚至可能吗?我假设我的第二个和第三个任务只会在前一个任务完成后运行.
我被告知如何编写代码:
public Task DoSomething()
{
return Task.Factory.StartNew(() =>
{
Console.WriteLine("Step 1");
})
.ContinueWith((prevTask) =>
{
prevTask.Wait();
Console.WriteLine("Step 2");
})
.ContinueWith((prevTask) =>
{
prevTask.Wait();
Console.WriteLine("Step 3");
});
}
Run Code Online (Sandbox Code Playgroud) 我有以下两个应用
我正在使用Angular的HttpClient向API 发出GET请求,如下所示
this.subscription = this.httpClient.get('api/Controller/LongRunningProcess')
.subscribe((response) =>
{
// Handling response
});
Run Code Online (Sandbox Code Playgroud)
API控制器的LongRunningProcess方法具有以下代码
[HttpGet]
[Route("LongRunningProcess")]
public async Task<IActionResult> LongRunningProcess(CancellationToken cancellationToken)
{
try
{
// Dummy long operation
await Task.Factory.StartNew(() =>
{
for (int i = 0; i < 10; i++)
{
// Option 1 (Not working)
if (cancellationToken.IsCancellationRequested)
break;
// Option 2 (Not working)
cancellationToken.ThrowIfCancellationRequested();
Thread.Sleep(6000);
}
}, cancellationToken);
}
catch (OperationCanceledException e)
{
Console.WriteLine($"{nameof(OperationCanceledException)} thrown with …
Run Code Online (Sandbox Code Playgroud) c# asp.net-core asp.net-core-webapi asp.net-core-2.0 angular
我有以下一段代码:
private void btnAction_Click(object sender, RoutedEventArgs e)
{
/** Clear the results field */
txtResult.Text = "";
/** Disable the button and show waiting status */
btnAction.IsEnabled = false;
lblStatus.Text = "Wait...";
/** Get input from the query field */
string input = query.Text;
/** Run a new task */
Task.Run(() => {
// calling a method that takes a long time (>3s) to finish and return
var attempt = someLibrary.doSomethingWith(input);
// return the result to the GUI thred
this.Dispatcher.Invoke(() …
Run Code Online (Sandbox Code Playgroud) 我正在尝试使用概念验证应用程序,我想知道下面两个异步方法的内部结构.
会Task.Result
导致任何问题DoSomethingAsync1()
吗?
我已经阅读了一些Task.Result
可能导致的阻塞和死锁问题,但我认为在这种情况下不会,因为它运行在一个单独的任务上,并且有一个await
已经确保结果的任务.
这里的主要目标是在单独的任务上运行异步方法,因为此操作不依赖于主asp.net线程,更重要的是捕获由抛出的任何异常 DoSomethingThatTakesReallyLong()
另外,在ActionResult
DoSomething()
,我应该设置.ConfigureAwait(false);
?
在下面的场景中,我是否需要注意隐藏的瓶颈/问题?
更新
我已经解决了我在这里输入问题时所做的拼写错误.(返回用户对象而不是任务)
而且,async
在实际应用中,我无权将所有更高级别的方法转换为一次性.所以,这是我打算一步一步地做的事情,从不依赖于主线程的操作开始.
我非常感谢所有最佳实践答案,但这是一个小游乐场代码,我的主要问题是要知道是否存在内部差异DoSomethingAsync1()
,DoSomethingAsync2()
这可能会导致某些条件下的任何问题.
从阅读评论和答案,我得到一个想法,没有太大的区别.
private static async Task<User> DoSomethingAsync1()
{
try
{
var longRunningTask = Task<User>.Factory.StartNew(() => LongRunner.LongRunnerInstance.DoSomethingThatTakesReallyLong());
var user = await longRunningTask;
//Will the below line of code cause any issue?
Console.WriteLine(longRunningTask.Result.Id);
return user;
}
catch (Exception ex)
{
Console.WriteLine(ex);
return null;
}
}
private static async Task<User> DoSomethingAsync2()
{
try
{ …
Run Code Online (Sandbox Code Playgroud) 这是我的C#
功能
public async Task GetAttendance(IEnumerable<Zone> zones)
{
try
{
foreach (var zone in zones)
{
var req = new AttendeeRequestTO(zone.StartTime, zone.EndTime, zone.ZoneId.ToString(), accessToken);
//THROWING COMPILE TIME ERROR
zone.AttendanceCount = Task.Factory.StartNew(() => _vClient.GetAttendeesCount(req));
}
}
catch (Exception ex)
{
}
}
Run Code Online (Sandbox Code Playgroud)
错误
错误 CS0029 无法将类型“System.Threading.Tasks.Task>”隐式转换为“int?”
我不想为每个任务应用等待,因为每个任务都是独立的,我希望每个任务在自己的上下文中运行,而无需等待任何其他任务。
我的意思是
任务T1-转到API,获取值并设置计数
任务T2-转到API,获取值并设置计数
任务T3-转到API,获取值并设置计数
T2 不应等待 T1 完成,T3 不应等待 T2 完成等等。
如何将每个任务的输出值分配给zone.AttendanceCount
?