如何使此循环异步?

时间:2018-02-03 04:10:43

标签: c# asynchronous

我试图获得它,以便在我的循环继续时,程序仍将运行,我尝试使用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();
    }
}

}

1 个答案:

答案 0 :(得分:0)

您可以使用async方法修饰符和await运算符,使用ReadToEndAsyncGetResponseAsync等方法来执行此操作。你可以通过 never 调用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);
        }
}