简体   繁体   English

如何运行无限线程?

[英]How to run an infinite thread?

I'm trying to run a Thread infinitely, but it's not working ... 我正在尝试无限运行一个线程,但是它不起作用...

Follow the code: 遵循代码:

namespace BTCPrice
{
    public static class Price
    {
        private static volatile bool _shouldStop = false;

        public static void RequestStop()
        {
            _shouldStop = true;
        }

        public static void Refresh(out string value, int tipo = 0, string source = "https://www.mercadobitcoin.net/api/")
        {
            while (_shouldStop == false)
            {

                JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

                WebClient cliente = new WebClient();

                string json = cliente.DownloadString(string.Format("{0}/{1}/{2}", source, "BTC", "ticker"));

                JObject j = JObject.Parse(json);

                switch (tipo)
                {
                    //Get High Price
                    case 0:
                        value = j["ticker"]["high"].ToString();
                        break;

                    //Get Low Price
                    case 1:
                        value = j["ticker"]["low"].ToString();
                        break;

                    default:
                        value = "default";
                        break;

                }

                Thread.Sleep(1000);
            }

            value = "Stopped";
        }
    }
}

On Start: 开始时:

string result = "";
Thread workerThread = new Thread(() => {
    Price.Refresh(out result);

    MessageBox.Show(result);

    Invoke(textBox1, result);

    Thread.Sleep(1000);
});

No exception occurs ... as long as I remove the While (_shouldStop == false) class the code works perfectly. 只要我删除While (_shouldStop == false)类,代码就可以正常工作。 However, I would like that, while the program is open, it executes the code and updates the textbox with the value that I get by the API. 但是,我想在程序打开时执行代码,并用我通过API获得的值更新文本框。

result without While(_shouldStop == false) in class: 类中没有While(_shouldStop == false)的结果:

Expected Result with While While的预期结果

You really shouldn't be using threads these days when there are excellent alternatives that handle all of the mess for you. 如今,当有出色的替代方案可以为您处理所有混乱时,您真的不应该使用线程。

I'd suggest using Microsoft's Reactive Framework (aka "Rx"). 我建议使用Microsoft的Reactive Framework(又名“ Rx”)。 Just NuGet "System.Reactive", "System.Reactive.Windows.Forms" (Windows Forms), "System.Reactive.Windows.Threading" (WPF). 只需NuGet“ System.Reactive”,“ System.Reactive.Windows.Forms”(Windows窗体),“ System.Reactive.Windows.Threading”(WPF)。

Then you can do this: 然后,您可以执行以下操作:

int tipo = 0;
string source = "https://www.mercadobitcoin.net/api/";

string url = string.Format("{0}/{1}/{2}", source, "BTC", "ticker");

IObservable<string> feed =
    from n in Observable.Interval(TimeSpan.FromSeconds(1.0))
    from json in Observable.Using<string, WebClient>(() => new WebClient(), cliente => cliente.DownloadStringTaskAsync(url).ToObservable())
    let j = JObject.Parse(json)
    let high = j["ticker"]["high"].ToString()
    let low = j["ticker"]["low"].ToString()
    select tipo == 0 ? high : (tipo == 1 ? low : "default");

IDisposable subscription =
    feed
        .ObserveOn(this); // for Windows Forms OR .ObservableOnDispatcher() for WPF
        .Subscribe(value =>
        {
            /* Do something with `value` */
        });

You'll now get a steady stream of the string value every second. 现在,您将每秒获得string稳定的string值。 A thread is started automatically and the results are automatically pasted to the UI thread. 线程自动启动,结果自动粘贴到UI线程。

When you want to stop the feed producing values just call subscription.Dispose(); 当您要停止供稿产生值时,只需调用subscription.Dispose(); .

This code entirely replaces your Price class. 该代码完全替代了Price类。

Change your while loop in Price.Refresh to inside the thread. 更改Price中的while循环。刷新到线程内部。 Have Price.Refresh return a string instead. 让Price.Refresh代替返回一个字符串。

Thread workerThread = new Thread(() => {
while (true)
{ 
    String result = Price.Refresh();

    MessageBox.Show(result);

    Invoke(textBox1, result);

    Thread.Sleep(1000); 
});

I agree with Scott Chamberlain in that you should use a timer instead and rewrite this but this will work for you. 我同意Scott Chamberlain的观点,您应该改用计时器并重写它,但这将对您有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM