如何判断Task.Run是否在循环内完成 [英] How to determine whether Task.Run is completed within a loop

查看:41
本文介绍了如何判断Task.Run是否在循环内完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个奇怪的问题,它确实是出于我的教育目的,因此我可以将其应用到未来可能出现的场景中.

This may be an odd question and it is really for my educational purpose so I can apply it in future scenarios that may come up.

我使用的是 C#.

我正在进行压力测试,所以这不是生产代码.

I am stress testing so this is not quite production code.

我通过网络服务将数据上传到我的服务器.

I upload data to my server via a web service.

我使用 Run.Task 启动服务.

I start the service off using a Run.Task.

在允许下一个 Run.Task 开始之前,我会检查任务是否已完成.

I check to see if the Task is completed before allowing the next Run.Task to begin.

这是在一个循环中完成的.

This is done within a loop.

但是,因为我使用的是模块化声明的 Task 会不会影响结果?我可以声明一个本地 Task.Run 变量,但我想看看第一个问题我能走多远.

However, because I am using a modular declared Task will not the result be affected? I could declare a local Task.Run variable but I want to see how far I can get with this question 1st.

如果 Task.Run 可以引发一个事件来表示它已完成,那么这可能不是问题吗?

If the Task.Run can raise an event to say it is completed then this may not be an issue?

这是我的代码:

//模块声明:

private static Task webTask = Task.Run(() => { System.Windows.Forms.Application.DoEvents(); });

//在通过定时器调用的函数中

//in a function called via a timer

if (webTask.IsCompleted)
{
   //keep count of competed tasks
}


webTask = Task.Run(() =>
{
    try 
    { 
         wcf.UploadMotionDynamicRaw(bytes);  //my web service
    }
    catch (Exception ex)
    {
        //deal with error
    }
);

推荐答案

IMO 你不需要计时器.使用任务继续订阅done 事件:

IMO you do not need the timer. Using Task Continuation you subscribe to the done event:

System.Threading.Tasks.Task
.Run(() => 
{
    // simulate processing
    for (var i = 0; i < 10; i++)
    {
        Console.WriteLine("do something {0}", i + 1);
    }
})
.ContinueWith(t => Console.WriteLine("done."));

输出为:

do something 1
do something 2
.
.
do something 9
do something 10
done

您的代码可能如下所示:

Your code could look like this:

var webTask = Task.Run(() =>
{
    try 
    { 
        wcf.UploadMotionDynamicRaw(bytes);  //my web service
    }
    catch (Exception ex)
    {
        //deal with error
    }
}).ContinueWith(t => taskCounter++);

如果您只想计算成功的任务 - 使用 TaskContinuationOptrions.

With task continuation you could even differentiate between failed and success process result, if you want to count only successfull tasks - using the TaskContinuationOptrions.

这篇关于如何判断Task.Run是否在循环内完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆