【问题标题】:How can I make this loop async?我怎样才能使这个循环异步?
【发布时间】:2018-02-03 04:10:42
【问题描述】:

我正在尝试获取它,以便在我的循环进行时,程序仍将运行,我尝试使用 async/await 组合但没有成功。我应该怎么做才能让程序在循环同时运行时顺利运行?
Btc 值被发送到一个标签,该标签会更新该值是什么

namespace WindowsFormsApp1
{
public static class Program
{
    public static string Btc;

    public static void SendRequest()
    {
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://api.coinbase.com/v2/prices/USD/spot?");
            using (var response = req.GetResponse())
                while (true)
                {
                    var html = new StreamReader(response.GetResponseStream()).ReadToEnd();
                    Btc = Regex.Match(html, "\"BTC\",\"currency\":\"USD\",\"amount\":\"([^ \"]*)\"}").ToString();
                    Thread.Sleep(300);
                }
        }
    }
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
        SendRequest();
    }
}

}

【问题讨论】:

  • async 方法修饰符和await 运算符与ReadToEndAsync等方法一起使用

标签: c# asynchronous


【解决方案1】:

您可以通过将async 方法修饰符和await 运算符与ReadToEndAsyncGetResponseAsync 等方法一起使用来实现此目的。您可以通过 从不 调用 Thread.Sleep 来执行此操作,这会阻塞调用线程。

public static string Btc;

public static async Task SendRequestAsync()
{
    var request = WebRequest.Create("https://api.coinbase.com/v2/prices/USD/spot?");
    using (var response = await request.GetResponseAsync())
        while (true)
        {
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                var html = await reader.ReadLineAsync();
                Btc = Regex.Match(html, @"""BTC"",""currency"":""USD"",""amount"":""([^ ""]*)""}").ToString();
            }
            await Task.Delay(300);
        }
}

【讨论】:

    猜你喜欢
    • 2020-08-14
    • 1970-01-01
    • 2023-03-23
    • 2017-12-20
    • 1970-01-01
    • 2017-06-25
    • 2020-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多