作为线程或任务启动异步方法 [英] Starting async method as Thread or as Task

查看:93
本文介绍了作为线程或任务启动异步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C# s await/async的新手,目前正在玩游戏.

I'm new to C#s await/async and currently playing around a bit.

在我的场景中,我有一个具有WebRequest属性的简单客户端对象.客户端应通过WebRequest s RequestStream定期发送活动消息. 这是客户端对象的构造函数:

In my scenario I have a simple client-object which has a WebRequest property. The client should send periodically alive-messages over the WebRequests RequestStream. This is the constructor of the client-object:

public Client()
{
    _webRequest = WebRequest.Create("some url");
    _webRequest.Method = "POST";

    IsRunning = true;

    // --> how to start the 'async' method (see below)
}

和异步alive-sender方法

and the async alive-sender method

private async void SendAliveMessageAsync()
{
    const string keepAliveMessage = "{\"message\": {\"type\": \"keepalive\"}}";
    var seconds = 0;
    while (IsRunning)
    {
        if (seconds % 10 == 0)
        {
            await new StreamWriter(_webRequest.GetRequestStream()).WriteLineAsync(keepAliveMessage);
        }

        await Task.Delay(1000);
        seconds++;
    }
}

该方法应如何启动?

新线程(SendAliveMessageAsync).Start();

new Thread(SendAliveMessageAsync).Start();

Task.Run(SendAliveMessageAsync);//将返回类型更改为Task

Task.Run(SendAliveMessageAsync); // changing the returning type to Task

等待SendAliveMessageAsync();//由于构造函数不异步而失败

await SendAliveMessageAsync(); // fails as of the constructor is not async

我的问题更多是关于我对await/async的个人理解,我认为在某些方面可能是错误的.

My question is more about my personal understanding of await/async which I guess may be wrong in some points.

第三个选择是投掷

The 'await' operator can only be used in a method or lambda marked with the 'async' modifier

推荐答案

该方法应如何启动?

How should the method be started?

我投票赞成以上皆非". :)

I vote for "none of the above". :)

失火忘却"是很难正确处理的情况.特别地,错误处理总是有问题的.在这种情况下,async void可能会让您感到惊讶.

"Fire and forget" is a difficult scenario to handle correctly. In particular, error handling is always problematic. In this case, async void may surprise you.

如果我不立即await立即执行任务,我希望明确保存任务:

I prefer to explicitly save the tasks if I'm not awaiting them immediately:

private async Task SendAliveMessageAsync();

public Task KeepaliveTask { get; private set; }

public Client()
{
  ...
  KeepaliveTask = SendAliveMessageAsync();
}

这至少允许Client的使用者检测并恢复SendAliveMessageAsync方法引发的异常.

This at least allows the consumers of Client to detect and recover from exceptions thrown by the SendAliveMessageAsync method.

另一方面,此模式几乎等同于我的 异步初始化"模式.

On a side note, this pattern is almost equivalent to my "asynchronous initialization" pattern.

这篇关于作为线程或任务启动异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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