-1

I found a few examples on the internet but I'm having a hard time trying to run my async call inside a background worker. I'm working in WP8. What's missing?

Edit: The purpose of this is to update the values I'm reading from time to time. Let's say 1s.

Here is my async code, it just gets and stores some data in providers []:

public void getAllProvidersMethod()
        {
            try
            {
                sc.getAllProvidersCompleted += new EventHandler<ServiceReference1.getAllProvidersCompletedEventArgs>(callback);
                sc.getAllProvidersAsync();
            }
            catch (System.Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }

public void callback(object sender, ServiceReference1.getAllProvidersCompletedEventArgs e)
        {
            try
            {
                providers = new String[e.Result.Length];
                for (int i = 0; i < e.Result.Length; i++)
                {
                    providers[i] = e.Result[i].ToString();
                }
            }
            catch (System.Exception d)
            {
                MessageBox.Show(d.ToString());
            }
        }

This is my background worker:

private void networkWorker()
        {
            var obj = App.Current as App;
            BackgroundWorker bw = new BackgroundWorker();

            bw.DoWork += new DoWorkEventHandler(
        delegate(object o, DoWorkEventArgs args)
        {
            BackgroundWorker b = o as BackgroundWorker;

                getAllProvidersMethod();

        });

            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
        delegate(object o, RunWorkerCompletedEventArgs args)
        {
            MessageBox.Show(" ");
        });

            bw.RunWorkerAsync();
        }
4

1 回答 1

0

好的,我设法让它工作!

对于任何想要不时自动运行一些异步代码的人,忘记后台工作者,你正在寻找的是一个计时器。感谢 Servy 的 Timer 提示。

假设我想asyncCall每 5 秒调用一次。

这很简单。首先定义调用之间的等待时间(您希望它在再次调用相同代码之前等待多长时间)。

System.Windows.Threading.DispatcherTimer dt = new System.Windows.Threading.DispatcherTimer();
dt.Interval = new TimeSpan(0, 0, 0, 0, 5000); // HERE - for example 5000 is 5 seconds
dt.Tick += new EventHandler(dt_Tick);
dt.Start();

然后你只需要在这个方法中编写你想要重复的代码:

void dt_Tick(object sender, EventArgs e)
{
            asyncCall();
}

在这种情况下,它会每 5 秒调用asyncCall.

于 2013-06-18T18:23:36.597 回答