【问题标题】:C# Winform get data from API every 10 seconds and save in folderC# Winform 每 10 秒从 API 获取数据并保存在文件夹中
【发布时间】:2019-09-29 13:28:48
【问题描述】:

我想每 10 秒向 API 发送 POST 数据并接收数据。接下来我想将接收到的数据解析为 json 并保存到文件中。我不想阻止用户界面。方法将 24 小时有效。

这是一个 C# Winforms 程序,用于从 API 下载数据并将其保存在本地磁盘上。

            printerThread = new Thread(new ThreadStart(InvokeMethod))
            {
                IsBackground = true
            };
            printerThread.SetApartmentState(ApartmentState.STA);
            printerThread.Start();

我期待轻量级解决方案 :)

【问题讨论】:

  • 您的代码并未真正反映您的问题。
  • 欢迎来到 SO!请看看如何提出正确的问题:meta.stackoverflow.com/questions/252585/…。我们不编写您的代码。
  • 我建议你使用后台工作者来防止阻塞 UI 线程。您也可以使用计时器来安排您的操作。每 10 秒调用一次 bgworker 中的 api。

标签: c# winforms thread-safety task threadpool


【解决方案1】:

你的问题其实可以分为三个部分
1. 每 10 秒发布一次 => Timer + WebClient
2. 获取数据,转换成JSON然后保存到文件 => JsonConvert + File.WriteAllText()
3. 不要阻塞 UI(我假设是请求线程本身)=> async await

您没有包含数据结构,但我想您可以自己查看 JsonConvert,其余部分的快速示例。

Timer timer = new Timer(async (state) =>
{
    string feedback = "";
    try
    {
        var uriOfAPI = new Uri("http://httpbin.org/post");
        using (WebClient webClient = new WebClient())
        {
            webClient.Headers["ContentType"] = "application/json";
            feedback = await webClient.UploadStringTaskAsync(uriOfAPI, "POST", "whatever the input should be");
        }
    }
    catch (Exception)
    {
        // how you are going to handle when API malfunction
    }

    // feedback convert to json(in this example, it already is)

    File.WriteAllText(@".\output.txt", feedback);

}, null, TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(10));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 2021-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    相关资源
    最近更新 更多