首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >线程停止,XMLexception错误

线程停止,XMLexception错误
EN

Stack Overflow用户
提问于 2014-02-25 00:23:35
回答 2查看 235关注 0票数 0

因此,我启动了一个线程计时器,它可以工作,但线程计时器中的方法从yahoo API读取XML,有时对服务器的响应很差,因此抛出了XMLexception。但这似乎会停止线程,因为线程启动得很好,但当抛出异常时,所有线程都会停止。那么到底是怎么回事,我可以在每次另一个线程停止的时候启动一个线程吗?因为所有线程都会停止,然后再没有线程启动。

代码语言:javascript
运行
复制
try
        {
            System.Threading.Timer timer;
            timer = new System.Threading.Timer(new TimerCallback(TimerHelper), null, 0, 3000);
        }
        catch (Exception)
        {

        }

TimerHelper(object obj)已尝试捕获异常。

代码语言:javascript
运行
复制
public void TimerHelper(object obj)
    {

        try
        {
            if (dataGridView.Rows.Count > 0 && !(dataGridView.Rows[0].Cells[0].Value == null)) // Updates the rows idividualy as long as first row is not empty
            {
                string[] cells;
                cells = new string[dataGridView.Columns.Count * dataGridView.Rows.Count];
                for (int i = 0; i < dataGridView.RowCount; i++)
                {
                    if (!(dataGridView.Rows[i].Cells[0].Value == null || dataGridView.Rows[i].Cells[0].Value.ToString() == "-")) // Makes sure that the row to update is not an empty row
                    {
                        String symbol;
                        symbol = Convert.ToString(dataGridView.Rows[i].Cells[0].Value);
                        String URLString2 = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22" + symbol + "%22)%0A%09%09&diagnostics=true&env=http%3A%2F%2Fdatatables.org%2Falltables.env";
                        for (int t = 2; t < dataGridView.Columns.Count; t++)
                        {
                            dataGridView.SuspendLayout();
                            XmlTextReader reader2 = new XmlTextReader(URLString2); // Makes the reader read from the string abow ( URL )
                            string NasdaqOpenTime = "09:00:00";

                            // if the market haven't been open for the day then theres no DaysLow value
                            if (dataGridView.Columns[t].HeaderText == "DaysLow" && DateTime.Now.CompareTo(DateTime.Parse(NasdaqOpenTime)) == -1)
                            {
                                cells[t - 2] = "0";
                            }

                            // if the market haven't been open for the day then theres no DaysHigh value
                            if (dataGridView.Columns[t].HeaderText == "DaysHigh" && DateTime.Now.CompareTo(DateTime.Parse(NasdaqOpenTime)) == -1)
                            {
                                cells[t - 2] = "0";
                            }
                            else
                            {
                                reader2.ReadToFollowing(dataGridView.Columns[t].HeaderText);  // Reada until it fins the elemnt Bid , then stops on it
                                reader2.ReadStartElement(dataGridView.Columns[t].HeaderText); // Recognizes Bid as start element (Bid)
                                string temporary;
                                temporary = reader2.ReadString();
                                Trace.WriteLine(dataGridView.Columns[t].HeaderText + ": " + temporary);
                                cells[t - 2] = temporary; // Reads the text in between (Declared as a string) actualy the bid value
                                reader2.ReadEndElement();  // Checks that the current nod is an end element (/Bid) if so then continue
                                reader2.ResetState();
                            }

                        }

                    }
                }
                for (int h = 0; h < dataGridView.Rows.Count; h++)
                {
                    for (int t = 2; t < dataGridView.Columns.Count; t++)
                    {
                        dataGridView.Rows[h].Cells[t].Value = cells[t - 2];
                    }
                }
            }
        }
        catch (XmlException)
        {
        }
        catch (Exception)
        {

        }
    }

下面是在TimerHelper(object obj)中跟踪的值的输出示例。

代码语言:javascript
运行
复制
    'FetchBySymbol.vshost.exe' (Managed (v4.0.30319)): Loaded 'C:\Users\Mattias\documents\visual studio 2012\Projects\FetchBySymbol\FetchBySymbol\bin\Debug\FetchBySymbol.exe', Symbols loaded.
    'FetchBySymbol.vshost.exe' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Configuration\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll'
    Ask: 37.44
    Bid: 37.43
...
...
...
    Ask: 37.44
    Bid: 37.43
    Ask: 37.42
    Bid: 37.41
    The thread '<No Name>' (0x104c) has exited with code 0 (0x0).
    The thread '<No Name>' (0x1920) has exited with code 0 (0x0).
    A first chance exception of type 'System.Net.WebException' occurred in System.dll
    A first chance exception of type 'System.Net.WebException' occurred in System.Xml.dll
    The thread '<No Name>' (0xe3c) has exited with code 0 (0x0).
    The thread '<No Name>' (0x1af0) has exited with code 0 (0x0).
    The thread '<No Name>' (0x1b18) has exited with code 0 (0x0).
    The thread '<No Name>' (0xb90) has exited with code 0 (0x0).
    The thread '<No Name>' (0x20) has exited with code 0 (0x0).

为什么它会退出?

EN

回答 2

Stack Overflow用户

发布于 2014-02-25 01:13:06

不要捕获泛型Exception,因为使用(来自您的帖子的代码)

代码语言:javascript
运行
复制
catch (Exception) { }

可能导致每个可能的Exception从您的手指间溜走的情况。

试着找出System.Net.WebException可能发生的地方,并命名你的线程,这样你就可以更深入地了解正在发生的事情,例如:

代码语言:javascript
运行
复制
(new Thread(() => {}) { Name = "Some thread" }).Start();

输出

代码语言:javascript
运行
复制
The thread 'Some thread' (0x260c) has exited with code 0 (0x0).

如果你想知道这些first chance exceptions是什么,请看这里http://blogs.msdn.com/b/davidklinems/archive/2005/07/12/438061.aspx

正如@BlackICE所说,请发布丢失的代码片段,以便解决您的问题。

编辑:

你确定你正在寻找正确的地方来解决这个问题吗?如前所述,线程退出不是问题的征兆(您确实希望线程在完成工作后退出),也不是第一次机会异常(抛出异常但已处理)。

这会不会是CGd计时器的问题,就像这篇文章所说的那样?

System.Threading.Timer not firing after some time

编辑:

试试这样的东西,好吗?它将永远以非阻塞的方式运行。只需添加一些更详细的异常处理;)。

代码语言:javascript
运行
复制
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
        Task.Factory.StartNew(() => DoTheMagic());
    }

    // Here the magic occurs
    public async Task DoTheMagic()
    {
        while (true)
        {
            string url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22YHOO%22)&diagnostics=true&env=http://datatables.org/alltables.env";
            string raw = await GetResponse(url);
            var parsed = await ParseXml(raw);

            // Pass results to UI
            Dispatcher.BeginInvoke(new Action(() =>
                {
                    if (parsed == null || !parsed.Any())
                        return;

                    var now = DateTime.Now;
                    foreach (var tuple in parsed)
                        textBox.Text += string.Format("{0} {1} = {2}{3}", now, tuple.Item1, tuple.Item2, Environment.NewLine);
                }));
            Thread.Sleep(3000);
        }
    }

    // Get response from service
    public async Task<string> GetResponse(string url)
    {
        string content = null;
        try
        {
            var request = WebRequest.Create(url);
            var response = await request.GetResponseAsync();
            var stream = response.GetResponseStream();

            if (stream == null)
                return null;

            using (var reader = new StreamReader(stream, Encoding.GetEncoding("utf-8")))
                content = await reader.ReadToEndAsync();
        }
        catch
        {
            System.Diagnostics.Debug.WriteLine("ZOMG!");
        }

        return content;
    }

    // Parse response with your logic
    public Task<List<Tuple<string, string>>> ParseXml(string xml)
    {
        return Task.Factory.StartNew(() =>
            {
                try
                {
                    var nodes = new string[] { "Symbol", "Ask", "Bid" };
                    var result = new List<Tuple<string, string>>();

                    using (var reader = new XmlTextReader(new StringReader(xml)))
                    {
                        reader.MoveToContent();
                        while (reader.Read())
                        {
                            if (reader.NodeType.Equals(XmlNodeType.Element))
                            {
                                if (nodes.Contains(reader.LocalName))
                                    result.Add(new Tuple<string, string>(reader.LocalName, reader.ReadElementContentAsString()));
                            }
                        }
                    }
                    return result;
                }
                catch
                {
                    System.Diagnostics.Debug.WriteLine("I haz exception!!1");
                    return null;
                }
            });
    }
}

输出

票数 0
EN

Stack Overflow用户

发布于 2014-02-25 02:00:09

线程退出是正常的,看看退出代码:

The thread '<No Name>' (0xe3c) has exited with code 0 (0x0).

这将在每次计时器触发时发生,并且从您的输出看,计时器是周期性地触发的(您会得到多个线程退出,显然是周期性的)。您可能希望在异常处理程序中放置一些东西,而不是只吃它们,然后您可以设置断点,并查看为什么对计时器处理程序的后续调用无法运行您的代码。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21993242

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档