Beispiel #1
0
        public static void acq_async_load_example2(string name, ExcelAsyncHandle asyncHandle)
        {
            //Native Excel async functions, that work only in Excel 2010+ (this is when your function takes an ExcelAsyncHandle as parameter and has return type "void")
            int managedThreadId = System.Threading.Thread.CurrentThread.ManagedThreadId;

            System.Threading.ThreadPool.QueueUserWorkItem(delegate(object state)
            {
                System.Threading.Thread.Sleep(2000);
                int completedThreadId = System.Threading.Thread.CurrentThread.ManagedThreadId;

                asyncHandle.SetResult(String.Format("{0} was loaded", name));
            });
        }
        public static void RunAsTask <TResult>(Func <TResult> function, ExcelAsyncHandle asyncHandle)
        {
            var task = Task.Factory.StartNew(function);

            task.ContinueWith(t =>
            {
                try
                {
                    // task.Result will throw an AggregateException if there was an error
                    asyncHandle.SetResult(t.Result);
                }
                catch (AggregateException ex)
                {
                    // There may be multiple exceptions...
                    // Do we have to call Handle?
                    asyncHandle.SetException(ex.InnerException);
                }

                // Unhandled exceptions here will crash Excel
                // and leave open workbooks in an unrecoverable state...
            }, TaskContinuationOptions.NotOnCanceled);
        }