C#:你能解释一下TaskFactory如何执行异步方法,该方法作为参数传递给StartNew方法吗?

时间:2017-11-15 06:43:01

标签: c# multithreading asynchronous threadpool

我对理解异步方法的执行存在问题,该方法作为参数传递给StartNew的{​​{1}}方法。你能解释一下它究竟会起作用吗?

我有TaskFactory类,其中包含用户标识符。

UserInfo

我有public sealed class UserInfo { [ThreadStatic] public static Guid UserId; } 的自定义实现。我没有显示此课程的完整代码,因为它并不有趣。此类将用户标识符设置为当前线程。将用户标识符设置为TaskScheduler变量。

UserId

我创建了自定义public sealed class CustomTaskScheduler : TaskScheduler { // Sets user information to the variable which is marked ThreadStatisAttribute. } ,它将自定义调度程序作为构造函数的参数。

TaskFactory

最后我有public sealed class CustomTaskFactory : TaskFactory { public CustomTaskFactory(CustomTaskScheduler taskScheduler) : base(taskScheduler) { } } 类执行异步操作。

Service

嗯,公平地说,我有两个问题:

  1. 来电public sealed class Service { private readonly CustomTaskScheduler customTaskScheduler; private readonly CustomTaskFactory customTaskFactory; private readonly SomeClient someClient; public Service() { this.customTaskScheduler = new CustomTaskScheduler(); this.customTaskFactory = new CustomTaskFactory(this.customTaskScheduler); this.someClient = new SomeClient(); } public void DoSomething(string param) { this.customTaskFactory.StartNew(() => testAsync(param)).Unwrap().Wait(); // This method will use the result which is given by async operation which is called above. DoSomethingElseSynchronously(); } private async Task DoSomethingAsync() { Thread.Sleep(1000); int result1 = await this.customTaskFactory.StartNew(() => PerformAsyncOperation(default(int))).Unwrap(); Thread.Sleep(1000); int result2 = await this.customTaskFactory.StartNew(() => PerformAsyncOperation(default(int))).Unwrap(); int sum = result1 + result2; } private async Task<int> PerformAsyncOperation(int x) { Thread.Sleep(1000); return await this.customTaskFactory.StartNew(() => CallClientAsync(x)).Unwrap(); } private async Task<int> CallClientAsync(int x) { Thread.Sleep(1000); int resultObtainedFromClient1 = await this.customTaskFactory.StartNew(async () => await this.someClient.GetAsync(x)).Unwrap(); Thread.Sleep(1000); int resultObtainedFromClient2 = await this.customTaskFactory.StartNew(async () => await this.someClient.GetAsync(x)).Unwrap(); int result = resultObtainedFromClient1 + resultObtainedFromClient2; return result; } } await this.customTaskFactory.StartNew(async () => await this.someClient.GetAsync(x)).Unwrap()有什么区别我想回忆一下,我对await this.customTaskFactory.StartNew(() => this.someClient.GetAsync(x)).Unwrap()变量ThreadStatic感兴趣。据我所知,第一个调用将在调用UserId方法的同一个线程中执行,在这种情况下我的线程静态字段将被填充。在第二个调用中,我将异步方法作为StartNew方法的参数。这意味着该任务将包含异步方法,该方法可能由另一个线程执行,而另一个线程将不包含我的StartNew变量。
    1. 我需要确保每个线程都不包含空的UserId变量。丢失UserId数据时是否有任何情况?怎么预防呢?
  2. 提前致谢

0 个答案:

没有答案