相关疑难解决方法(0)

UI线程上的任务继续

是否有一种"标准"方式来指定任务延续应该在创建初始任务的线程上运行?

目前我有下面的代码 - 它正在工作,但跟踪调度程序和创建第二个动作似乎是不必要的开销.

dispatcher = Dispatcher.CurrentDispatcher;
Task task = Task.Factory.StartNew(() =>
{
    DoLongRunningWork();
});

Task UITask= task.ContinueWith(() =>
{
    dispatcher.Invoke(new Action(() =>
    {
        this.TextBlock1.Text = "Complete"; 
    }
});
Run Code Online (Sandbox Code Playgroud)

.net c# wpf multithreading task

205
推荐指数
5
解决办法
9万
查看次数

当前的SynchronizationContext可能不会用作TaskScheduler

我正在使用Tasks在我的ViewModel中运行长时间运行的服务器调用,结果将被重新编组Dispatcher使用TaskScheduler.FromSyncronizationContext().例如:

var context = TaskScheduler.FromCurrentSynchronizationContext();
this.Message = "Loading...";
Task task = Task.Factory.StartNew(() => { ... })
            .ContinueWith(x => this.Message = "Completed"
                          , context);
Run Code Online (Sandbox Code Playgroud)

这在我执行应用程序时工作正常.但是当我运行我的NUnit测试时,Resharper我在调用时收到错误消息FromCurrentSynchronizationContext:

当前的SynchronizationContext可能不会用作TaskScheduler.

我想这是因为测试是在工作线程上运行的.如何确保测试在主线程上运行?欢迎任何其他建议.

c# multithreading nunit task-parallel-library resharper-6.0

96
推荐指数
2
解决办法
3万
查看次数

我怎样才能实现模式承诺/延期?

我想写一个Promise/Deffered模式.完美的变体到底是:

MyObject().CallMethodReturningPromise()
   .done( result => {
       ...something doing;
   } )
   .fail( error => {
       ...error handle;
   } )
   .always( () => {
       ...some code;
   } )
Run Code Online (Sandbox Code Playgroud)

我发现了这个实现https://bitbucket.org/mattkotsenas/c-promises/overviewhttps://gist.github.com/cuppster/3612000.但是我怎么能用它来解决我的任务?

c# promise

31
推荐指数
2
解决办法
2万
查看次数

.NET 是否在新的不同线程池线程上恢复等待继续,还是重用先前恢复的线程?

.NET 是否在新的不同线程池线程上恢复等待继续,还是重用先前恢复的线程?

让我们在下面的 .NET Core 控制台应用程序中的 C# 代码中想象一下:

using System;
using System.Threading;
using System.Threading.Tasks;

namespace NetCoreResume
{
    class Program
    {
        static async Task AsyncThree()
        {
            await Task.Run(() =>
            {
                Console.WriteLine($"AsyncThree Task.Run thread id:{Thread.CurrentThread.ManagedThreadId.ToString()}");
            });

            Console.WriteLine($"AsyncThree continuation thread id:{Thread.CurrentThread.ManagedThreadId.ToString()}");
        }

        static async Task AsyncTwo()
        {
            await AsyncThree();

            Console.WriteLine($"AsyncTwo continuation thread id:{Thread.CurrentThread.ManagedThreadId.ToString()}");
        }

        static async Task AsyncOne()
        {
            await AsyncTwo();

            Console.WriteLine($"AsyncOne continuation thread id:{Thread.CurrentThread.ManagedThreadId.ToString()}");
        }

        static void Main(string[] args)
        {
            AsyncOne().Wait();

            Console.WriteLine("Press any key to end...");
            Console.ReadKey();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

它会输出:

AsyncThree …
Run Code Online (Sandbox Code Playgroud)

c# multithreading asynchronous async-await

4
推荐指数
1
解决办法
823
查看次数