本文介绍了如何将ThreadPool.QueueUserWorkItem与非静态方法一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试编译时,它会给我

When I try to compile it gives me

因此,我将print标记为static,它可以工作.但是在更大的程序中,我有非静态方法.那么如何在这些方法中使用ThreadPool?

So, I marked print as static and it works. But in a bigger program I have non-static methods. So how do I use ThreadPool with those methods?

class Program
{
    static void Main(string[] args)
    {
        ThreadPool.QueueUserWorkItem(o => print("hello"));
        Console.ReadLine();
    }

    public void print(string s)
    {
        Console.WriteLine(s);
    }
}

推荐答案

您只需要一个实例即可对其进行操作:

You just need an instance to operate on:

var myObject = new WhateverClassItIs();
ThreadPool.QueueUserWorkitem(o => myObject.SomeMethod("some input"));

请记住,如果您使用的类型实现了IDisposable(或其他某种清除机制),则在确定异步操作已完成(或在异步操作结束时)之前,不应调用Dispose.操作本身).

Keep in mind that if the type that you use implements IDisposable (or some other cleanup mechanism), you should not invoke Dispose until you are certain that the asynchronous operation is completed (or at the end of the asynchronous operation itself).

这篇关于如何将ThreadPool.QueueUserWorkItem与非静态方法一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 22:07