线程化时C#InvalidOperationException

时间:2016-09-28 09:52:21

标签: c# wpf multithreading

我试图让函数每200毫秒运行一次,这样就可以显示程序首次启动和现在之间的时差。我尝试使用此代码进行线程处理:

Title.Content = span.ToString().Substring(0, 8); //gets first 8 characters (taking out milliseconds)

但这只会引发异常' InvalidOperationException'并说"附加信息:调用线程无法访问此对象,因为另一个线程拥有它。"关于第48行

namespace ComputerTimer
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private DateTime startTime, endTime;
        private DispatcherTimer dtClockTime;

        public MainWindow()
        {
            InitializeComponent();

            startTime = DateTime.Now;

            dtClockTime = new DispatcherTimer();

            dtClockTime.Interval = new TimeSpan(0, 0, 0, 0, 200); //in days, Hour, Minutes, Seconds, millis
            dtClockTime.Tick += dtClockTime_Tick;

            dtClockTime.Start();

        }

        private void dtClockTime_Tick(object sender, EventArgs e)
        {
            endTime = DateTime.Now;
            TimeSpan span = endTime - startTime; //gets difference between now and when the program was started
            Title.Content = span.ToString().Substring(0, 8);
        }

        private void btnStop_Click(object sender, RoutedEventArgs e)
        {
            //when button is pressed to stop timer
            dtClockTime.Stop();
        }
    }
}

我很困惑从这里做什么,并且已经搜索了所有堆栈溢出寻找答案,但似乎没有任何工作。我也尝试过DispatcherTimer,但没有运气。

编辑:这个答案对我来说对未来的任何人都有用

function getElements(inputs) {
    var elements = [],
            promise, whenPromise,
            promises = [],
            mainPromise = $q.defer();
    if (inputs.length === 0) {
        mainPromise.resolve(elements);
        return mainPromise.promise;
    }

    angular.forEach(inputs, function (input) {
        promise = getPromises(input);
        whenPromise = promise.then(function (response) {

            if (response.isEmpty) {
                * *//perform action with the response.data;**
            }

        }, function () {

        });

        promises.push(whenPromise);
    });


    return $q.all(promises).finally(function () {
        return outdatedEntities;
    });
}

function getPromises(input) {
    return someSerivce.getItemDetails(input.Id).then(function (value) {
        if (value === null) {
            return {data: input, isEmpty: true};
        } else {
            //have item locally, but need to see if it's current
            return input.isEmpty().then(function (isEmpty) {
                return {data: input, isEmpty: isEmpty};
            }, function (error) {
                return error;
            });
        }
    });
}

1 个答案:

答案 0 :(得分:0)

你在计时器Tick事件中创建了一个无限循环,你不应该有一个while(x)循环。

private void timer1_Tick(object sender, EventArgs e)
{
     endTime = DateTime.Now;
     TimeSpan span = endTime - startTime; //gets difference between now and when the program was started
     Title.Content = span.ToString().Substring(0, 8); //gets first 8 characters (taking out milliseconds)
 }

你的停止按钮应该只是禁用定时器

private void btnStop_Click(object sender, RoutedEventArgs e)
{
     timer1.Enabled = false;
}

编辑:可能需要设置计时器的SynchronisingObject

timer1.SynchronisingObject = this;

如果对于wpf应用程序失败了(对不起,我最初错过了标记),您应该使用DispatcherTimer代替System.Timers.Timer

设置与现有代码大致相同,它只使用不同类型的计时器,在正确的(UI)线程上引发tick事件。

顺便说一句,没有必要将mash一个字符串DateTime对象,有一些方法可以格式化一个时间跨度

Title.Content = span.ToString("mm:ss.ffff");