C#异步任务的股票代码 [英] C# Asynchronous Task for a Stock Ticker

查看:135
本文介绍了C#异步任务的股票代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直想了解更多关于异步任务和线程,但赚不到一吨的进展的。

我试图加载一个发动机型线,将在启动时在后台运行,并能够访问UI线程来更新变量,无需挂在UI线程。

在低于code,发动机被调用,并且北京时间创建对象持有(莱特币/ USD)被称为最后的当前值,还持有其它几个值,这将是有益的。这code成功地分配电流值label1.text。我不一定需要code,但我会采取什么样的方式来创建每秒背景的股票对象,并更新与每个新体育讯北京时间UI线程对象值。

这是一个很好的案例为背景的员工?

 私人无效Form1_Load的(对象发件人,EventArgs的发送)
    {
        发动机();
    }
    私人无效引擎()
    {
        新浪体育讯北京时间ltcusd = BtceApi.GetTicker(BtcePair.LtcUsd);
        label1.Text =LTC / USD:+ ltcusd.Last;
    }

编辑:
如果我这样做,LABEL1引发InvalidOperationException由于跨线程操作的企图(LABEL1在UI线程)。

 私人无效Form1_Load的(对象发件人,EventArgs的发送)
    {
        变种T = Task.Factory.StartNew(()=>引擎());
        t.Start();
    }
    私人无效引擎()
    {
        而(真)
        {
            Thread.sleep代码(1000);
            新浪体育讯北京时间ltcusd = BtceApi.GetTicker(BtcePair.LtcUsd);
            label1.Text =LTC / USD:+ ltcusd.Last;
        }
    }


解决方案

使用异步 / 等待,最简单的收到异步之类的API的方法是调用一个新的任务。这不是很大,但它会让事情变得更简单。我可能会创建一个新的类,它基本上包裹在任务所有的 BtceApi 方法:

 公共类BtceApiAsync
{
    公共任务<&新浪体育讯北京时间GT; GetTickerAsync(BtcePair对)
    {
        返回Task.Run(()=> BtceApi.GetTicker(对));
    }    //等
}

然后你可以使用一个计时器,触发每秒一次,这将相应地开始一个新的任务和更新用户界面:

  //保存类型System.Windows.Forms.Timer的领域
定时器=新定时器();
timer.Interval = 1000;
timer.Tick + = DisplayTicker;
timer.Start();...私人异步无效DisplayTicker(对象发件人,EventArgs的发送)
{
    新浪体育讯北京时间股票=等待BtceApiAsync.GetTickerAsync(BtcePair.LtcUsd);
    label1.Text =LTC / USD:+ ltcusd.Last;
}

请注意,这并不意味着屏幕会的更新的每秒一次......会有一个新的任务的每秒启动一次,并尽快每个任务完成后,用户界面​​将被更新。

使用等待在这里 - 从异步方法在UI线程上开始 - 意味着你无需担心使用的用户界面;整个异步方法将执行在UI线程上,即使取本身发生在不同的线程。

I've been trying to learn more about asynchronous tasks and threading but not making a ton of headway.

I'm trying to load an "Engine" type of thread that will run in the background upon launch and be able to access the UI Thread to update variables, without hanging the UI Thread.

In the below code, Engine is called, and a Ticker object is created which holds the current value of (Litecoin/USD) called Last, also holds several other values that would be useful. This code successfully assigns the current value to label1.text. I don't necessarily need code but what approach would I take to create a ticker object in the background every second and update the UI thread with each new Ticker objects values.

Is this a good case for a background worker?

    private void Form1_Load(object sender, EventArgs e)
    {
        Engine();
    }
    private void Engine()
    {
        Ticker ltcusd = BtceApi.GetTicker(BtcePair.LtcUsd);
        label1.Text = "LTC/USD:" + ltcusd.Last;
    }

EDIT: If I do the following, label1 throws an InvalidOperationException due to a Cross-thread operation attempt (label1 in the UI thread).

    private void Form1_Load(object sender, EventArgs e)
    {
        var t = Task.Factory.StartNew(() => Engine());
        t.Start();
    }
    private void Engine()
    {
        while (true)
        {
            Thread.Sleep(1000);
            Ticker ltcusd = BtceApi.GetTicker(BtcePair.LtcUsd);
            label1.Text = "LTC/USD: " + ltcusd.Last;
        }
    }

解决方案

Using async/await, the simplest way of getting an "asynchronous" sort of API is to invoke a new task. It's not great, but it'll make things simpler. I would probably create a new class which basically wrapped all the BtceApi methods in tasks:

public class BtceApiAsync
{
    public Task<Ticker> GetTickerAsync(BtcePair pair)
    {
        return Task.Run(() => BtceApi.GetTicker(pair));
    }

    // etc
}

Then you can use a timer which fires once per second, which will start off a new task and update the UI appropriately:

// Keep a field of type System.Windows.Forms.Timer
timer = new Timer();
timer.Interval = 1000;
timer.Tick += DisplayTicker;
timer.Start();

...

private async void DisplayTicker(object sender, EventArgs e)
{
    Ticker ticker = await BtceApiAsync.GetTickerAsync(BtcePair.LtcUsd);
    label1.Text = "LTC/USD: " + ltcusd.Last;
}

Note that this doesn't mean the screen will be updated once per second... there will be a new task started once per second, and as soon as each task completes, the UI will be updated.

The use of await here - from an async method started on the UI thread - means you don't need to worry about using the UI; the whole async method will execute on the UI thread, even though the fetch itself happens in a different thread.

这篇关于C#异步任务的股票代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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