如何运行无限线程?

时间:2017-08-30 19:22:58

标签: c# multithreading

我试图无限地运行一个线程,但它没有工作......

按照代码:

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";
        }
    }
}

开始时间:

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

    MessageBox.Show(result);

    Invoke(textBox1, result);

    Thread.Sleep(1000);
});

不会发生异常...只要我删除While (_shouldStop == false)类,代码就能完美运行。但是,我希望,当程序打开时,它会执行代码并使用API​​获取的值更新文本框。

在课堂上没有While(_shouldStop == false)的结果:

Expected Result with While

2 个答案:

答案 0 :(得分:4)

这些天你真的不应该使用线程,因为有很好的替代方案可以为你处理所有混乱。

我建议使用Microsoft的Reactive Framework(又名" Rx")。只是NuGet" System.Reactive"," System.Reactive.Windows.Forms" (Windows窗体)," System.Reactive.Windows.Threading" (WPF)。

然后你可以这样做:

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` */
        });

您现在每秒都会获得string值的稳定流。线程自动启动,结果自动粘贴到UI线程。

如果要停止Feed生成值,只需调用subscription.Dispose();

此代码完全取代您的Price类。

答案 1 :(得分:0)

将Price.Refresh中的while循环更改为线程内部。让Price.Refresh返回一个字符串。

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

    MessageBox.Show(result);

    Invoke(textBox1, result);

    Thread.Sleep(1000); 
});

我同意Scott Chamberlain的意见,你应该使用计时器并重写它,但这对你有用。